Is there a “All Children loaded” event in WPF

后端 未结 7 950
陌清茗
陌清茗 2020-12-13 02:49

I am listening for the loaded event of a Page. That event fires first and then all the children fire their load event. I need an event that fires when ALL the children have

相关标签:
7条回答
  • 2020-12-13 03:11

    You can also use the event: ContentRendered.

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

    0 讨论(0)
  • 2020-12-13 03:11

    I ended up doing something along these lines.. your milage may vary.

    void WaitForTheKids(Action OnLoaded)
    {
      // After your children have been added just wait for the Loaded
      // event to fire for all of them, then call the OnLoaded delegate
    
      foreach (ContentControl child in Canvas.Children)
      {
        child.Tag = OnLoaded; // Called after children have loaded
        child.Loaded += new RoutedEventHandler(child_Loaded);
      }
    }
    internal void child_Loaded(object sender, RoutedEventArgs e)
    {
      var cc = sender as ContentControl;
      cc.Loaded -= new RoutedEventHandler(child_Loaded);
    
      foreach (ContentControl ctl in Canvas.Children)
      {
        if (!ctl.IsLoaded)
        {
          return;
        }
      }
      ((Action)cc.Tag)();
    }
    
    0 讨论(0)
  • 2020-12-13 03:14

    Loaded is the event that fires after all children have been Initialized. There is no AfterLoad event as far as I know. If you can, move the children's logic to the Initialized event, and then Loaded will occur after they have all been initialized.

    See MSDN - Object Lifetime Events.

    0 讨论(0)
  • 2020-12-13 03:18

    WPF cant provide that kind of an event since most of the time Data is determining whther to load a particular child to the VisualTree or not (for example UI elements inside a DataTemplate)

    So if you can explain your scenario little more clearly we can find a solution specific to that.

    0 讨论(0)
  • 2020-12-13 03:19

    One of the options (when content rendered):

    this.LayoutUpdated += OnLayoutUpdated;

    private void OnLayoutUpdated(object sender, EventArgs e)
                {
                    if (!isInitialized && this.ActualWidth != 0 && this.ActualHeight != 0)
                    {
                        isInitialized = true;
                        // Logic here
                    }
                };
    
    0 讨论(0)
  • 2020-12-13 03:22

    I had the same problem. @configurator is right, if you are having this problem then I believe it is because you have a problem with your child elements. In my case the child elements where a custom user control. I was initializing them incorrectly. I fixed the user control and everything worked great

    0 讨论(0)
提交回复
热议问题