Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: What is between the Initialized and Loaded event?

I want to run some code when the Window or Control is first displayed. I can't use Loaded because that can fire more than once. I can't use Initialized because that is done by the constructor.

Is there an event somewhere between?

like image 697
Jonathan Allen Avatar asked Jul 21 '10 19:07

Jonathan Allen


People also ask

What is the difference between page and window in WPF?

Window is the root control that must be used to hold/host other controls (e.g. Button) as container. Page is a control which can be hosted in other container controls like NavigationWindow or Frame. Page control has its own goal to serve like other controls (e.g. Button). Page is to create browser like applications.


3 Answers

Unfortunately there is no such event. You can use a boolean in the Loaded Method to make sure your stuff only fires once -

if(!IsSetUp)
{
   MySetUpFunction();
   IsSetUp = true;
}

Check out the WPF Windows lifetime events here:

http://msdn.microsoft.com/en-us/library/ms748948.aspx#Window_Lifetime_Events

alt text
(source: microsoft.com)

like image 64
brendan Avatar answered Oct 18 '22 19:10

brendan


Alternatively to storing a boolean flag, you can use an extension method and delegate wrapping to fake Loaded only firing once.

public static void OnLoadedOnce(
    this UserControl control,
    RoutedEventHandler onLoaded)
{
    if (control == null || onLoaded == null)
    {
        throw new ArgumentNullException();
    }

    RoutedEventHandler wrappedOnLoaded = null;
    wrappedOnLoaded = delegate(object sender, RoutedEventArgs e)
    {
        control.Loaded -= wrappedOnLoaded;
        onLoaded(sender, e);
    };
    control.Loaded += wrappedOnLoaded;
}

...

class MyControl : UserControl
{
    public MyControl()
    { 
        InitializeComponent();
        this.OnLoadedOnce(this.OnControlLoaded /* or delegate {...} */);
    }

    private void OnControlLoaded(object sender, RoutedEventArgs e)
    {
    }
}
like image 22
DuckMaestro Avatar answered Oct 18 '22 20:10

DuckMaestro


If you don't want to use the boolean method of doing things, then you can create a method and subscribe to the Loaded event with it, then unsubscribe at the end of that method.

Example:

public MyDependencyObject(){
  Loaded += OnLoaded;
}

private void OnLoaded(object sender, EventArgs args){
  DoThings();
  Loaded -= OnLoaded;
}
like image 4
ryuk Avatar answered Oct 18 '22 20:10

ryuk