4imble
4imble

Reputation: 14416

Bad practice to put code directly after InitializeComponent?

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?

Upvotes: 1

Views: 1675

Answers (3)

Not just for fun
Not just for fun

Reputation: 39

I propose to put in Page_Loaded()

Loaded -= Page_Loaded

and then it won't execute again.

Upvotes: 0

ChrisF
ChrisF

Reputation: 137108

As you point out the Page_Loaded event will be fired each time the page is refreshed, so if you want the code to only be executed the once, then putting it in the constructor is the logical place.

Depending on how much code you need you might want to consider refactoring it into another method - but that's purely a matter of personal taste (or perhaps following coding standards).

UPDATE

I would guess that as the query used to generate tehBuildings is returning null (stating the obvious) then there's some other code you need to call before calling getBuildings. Without seeing your original code I wouldn't like to say what's now missing.

Upvotes: 1

Anderson Imes
Anderson Imes

Reputation: 25640

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.

Upvotes: 5

Related Questions