WPF, Bad practice to put code directly after InitializeComponent?

I was just interested in something. I have a frame that loads pages, and currently every page has a Page_Loaded method that will run every time the page is available. This works fine, but I notice errors if I use navigation to go to previously visited pages. Upon returning to the page, Page_Loaded is called again, which I do not need.

Using debugging, I noticed that InitializeComponent was called only on the first page call and was wondering if I could just put the Page_Loaded code after this call like this:

 public partial class MyPage: Page { public MyPage() { InitializeComponent(); //======> To Here } private void Page_Loaded(object sender, RoutedEventArgs e) { //Put Code from here <====== } } 

This will solve my problem, but is this a bad practice? And if so, what problems can I encounter in the future?

Thanks Cohan

+2
source share
2 answers

It is legal to do something in the constructor. I think this is normal.

WPF is not exactly like ASP.NET in terms of accessibility of objects / etc. It is a little weaker, and therefore something in the constructor does not quote no-no, it is in ASP.NET.

+5
source

As you noted, the Page_Loaded event will be fired every time the page is refreshed, so if you want the code to be executed only once, then placing it in the constructor is a logical place.

Depending on how much code you need, you might consider reorganizing it into another method - but this is purely a matter of personal taste (or perhaps the following coding standards).

UPDATE

I would suggest that since the query used to generate tehBuildings returns null (indicating the obvious), then you must call another code before calling getBuildings . Without seeing my source code, I would not want to say what is missing now.

+1
source

Source: https://habr.com/ru/post/920465/


All Articles