I was just wondering about something. I have a frame that loads pages and currently each page has a Page_Loaded method that will run each time the page is accessed. This is working great, but I am noticing errors if I use the navigation to go to previously visited pages. Upon returning to a page, Page_Loaded is being called again which I do not want.
Using debugging, I noticed that InitializeComponent was only getting called the first time the page is implemented and wondered if I could simply put my Page_Loaded code after this call like so:
public partial class MyPage: Page
{
public MyPage()
{
InitializeComponent();
//======> To Here
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
//Put Code from here <======
}
}
This would solve my problem but is a bad practice? And if so, what problems might I encounter down the road?
It’s legitimate to do something in the constructor. I think this is fine.
WPF isn’t quite like ASP.NET in terms of accessibility of objects / etc. It’s a bit looser and so doing something in a constructor isn’t quote the no-no it is in ASP.NET.