OnNavigatedTo vs Load Event

In several online examples, I found this:

public partial class ForecastPage : PhoneApplicationPage { Forecast forecast; public ForecastPage() { InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { // code here } } 

but in others I found using the Load event like

 public partial class Person : PhoneApplicationPage { private PersonViewModel _ViewModel; public Person() { InitializeComponent(); this.Loaded += new RoutedEventHandler(SearchView_Loaded); } void SearchView_Loaded(object sender, RoutedEventArgs e) { // code here } } 

I know that OnNavigatedTo fires before the Load event, but both lights before the user interface is pulled into the phone, so my question is there any advantages to using one method from the other?

+6
source share
3 answers

Reading documentation about OnNavigatedTo :

Called when the page becomes the active page in the frame.

and when we read about the Loaded event, see below:

Occurs when a FrameworkElement was created and added to the object tree.

They are completely different, like a page, correct me, if I am mistaken, they can become active more than once during the time of your application, but the creation of FrameworkElement usually happens once.

+7
source

I would not agree with Tigran.

 public View() { InitializeComponent(); personList.ItemsSource = PersonDataSource.CreateList(100); Loaded += (sender, args) => Debug.WriteLine("Loaded"); } protected override void OnNavigatedTo(NavigationEventArgs e) { Debug.WriteLine("Navigated"); } 

When moving back and forth output

switching loaded ship control loaded ship control Loaded

So, OnNavigated is called when the page is navigating , but before (during) the page controls are loaded, and Loaded is called when the page is ready, and all controls are loaded .

+23
source

On Windows Runtime, the Loaded event always fires after OnNavigatedTo (even if pages are cached using the NavigationCacheMode.Required parameter). Vitaly is right about this.

According to MSDN:

In the Windows Runtime implementation, the Loaded event is guaranteed to occur after applying the control template, and you can get links to objects created using the XAML template.

For application code that uses page navigation, do not use Page.OnNavigatedTo to control items or change the state of controls on the landing page. The OnNavigatedTo virtual method is called before the template is loaded, so the elements from the templates are not yet available. Instead, add the Loaded event handler to root from the recently loaded page content and perform any element of manipulation, state changes, posting events, etc. in the Loaded event handler.

But there is a good reason why you would like to use OnNavigatedTo: this is the only place where you can get navigation options. If you never use navigation options, use the Loaded event.

+1
source

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


All Articles