Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loaded event not exactly loaded

I feel silly, but I just can't find an answer to this. Let's say I want to show some message to the users when the MainPage loads. The problem is that if I do this on Loaded event (MessageBox.Show()), the popup shows just before my page is loaded which leaves the user with this message and a black background. This is kind of dull situation. Any ideas which event can do the trick. There other ways around like background worker or NavigationInTransition_EndTransition event but there should be more elegant way ?

like image 543
Miro Avatar asked Jun 28 '11 18:06

Miro


2 Answers

You can easily test all standard methods. It took me less time than writing this text to do so.

In page constructor:

Loaded += new RoutedEventHandler(TestPage_Loaded);
LayoutUpdated += new EventHandler(TestPage_LayoutUpdated);

Respective methods:

    void TestPage_LayoutUpdated(object sender, EventArgs e)
    {
        Debug.WriteLine("LayoutUpdated");
    }

    void TestPage_Loaded(object sender, RoutedEventArgs e)
    {
        Debug.WriteLine("Loaded");
        Dispatcher.BeginInvoke(() =>
        {
            Debug.WriteLine("Loaded -> BeginInvoke");
        });
    }

Add debug write to OnNavigateTo() as well.

If your page is similarly complex than mine, then you get something like:

  1. OnNavigatedTo
  2. LayoutUpdated
  3. Loaded
  4. LayoutUpdated
  5. Loaded -> BeginInvoke
  6. many times LayoutUpdated

Last LayoutUpdated would be the best candidate, but how would one detect it? Hence "Loaded -> BeginInvoke" seems to be the best option among the trivial ones.

You can also use the Loaded events of individual components on your page. That's also trivially easy. They will probably happen sometimes between 4th and 5th step.

If none of above options helps (I don't think so), you have to use non-standard logic. Such as above mentioned one-shot timer that shows the message after some time. Or base your logic on LayoutUpdated counter.

like image 119
Jan Slodicka Avatar answered Oct 27 '22 13:10

Jan Slodicka


If Loaded fires to early for you, you could try LayoutUpdated. This event is fired each time a layout pass occurs, and typically will fire after Loaded. However, you should remember to unsubscribe to this event when no longer needed. I use this event in the DeferredLoadContentControl which I created:

http://www.scottlogic.co.uk/blog/colin/2011/01/windows-phone-7-deferredloadcontentcontrol/

like image 22
ColinE Avatar answered Oct 27 '22 13:10

ColinE