WPF: What is between the Initialized and Loaded event?

别等时光非礼了梦想. 提交于 2020-01-22 06:52:46

问题


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?


回答1:


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


(source: microsoft.com)




回答2:


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)
    {
    }
}



回答3:


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;
}


来源:https://stackoverflow.com/questions/3302987/wpf-what-is-between-the-initialized-and-loaded-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!