WPF: What is between the Initialized and Loaded event?

前端 未结 3 805
悲哀的现实
悲哀的现实 2021-02-02 11:30

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

3条回答
  •  悲哀的现实
    2021-02-02 11:49

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

提交回复
热议问题