WPF:UIElement以及FrameworkElement中常见事件的运行顺序

测试如下事件和方法:

UIElement:

OnRender方法。

LayoutUpdated事件。

 

FrameworkElement:

OnMeasureOverride方法。

OnArrangeOverride方法。

Loaded事件。

Initialized事件。

 

以及自定义控件中的依赖属性设置。



class TestControl: Control

{

    public TestControl()

    {

        Loaded += new RoutedEventHandler(TestControl_Loaded);

        Initialized += new EventHandler(TestControl_Initialized);

        LayoutUpdated += new EventHandler(TestControl_LayoutUpdated);

    }

 

    #region Prop

 

    public static readonly DependencyProperty PropProperty =

        DependencyProperty.Register("Prop", typeof(bool), typeof(TestControl),

            new FrameworkPropertyMetadata((bool)false,

                FrameworkPropertyMetadataOptions.AffectsRender,

                new PropertyChangedCallback(OnPropChanged),

                new CoerceValueCallback(CoerceProp)));

 

    public bool Prop

    {

        get { return (bool)GetValue(PropProperty); }

        set { SetValue(PropProperty, value); }

    }

 

    private static void OnPropChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

    {

        Debug.WriteLine("DP:Changed");

    }

 

    private static object CoerceProp(DependencyObject d, object value)

    {

        Debug.WriteLine("DP:Coerce");

        return value;

    }

 

    #endregion

 

 

    void TestControl_LayoutUpdated(object sender, EventArgs e)

    {

        Debug.WriteLine("UIElement.LayoutUpdated");

    }

 

    void TestControl_Initialized(object sender, EventArgs e)

    {

        Debug.WriteLine("FrameworkElement.Initialized");

    }

 

    void TestControl_Loaded(object sender, RoutedEventArgs e)

    {

        Debug.WriteLine("FrameworkElement.Loaded");

    }

 

    protected override Size MeasureOverride(Size constraint)

    {

        Debug.WriteLine("FrameworkElement.MeasureOverride");

        return base.MeasureOverride(constraint);

    }

    protected override Size ArrangeOverride(Size arrangeBounds)

    {

        Debug.WriteLine("FrameworkElement.ArrangeOverride");

        return base.ArrangeOverride(arrangeBounds);

    }

    protected override void OnRender(DrawingContext drawingContext)

    {

        Debug.WriteLine("UIElement.OnRender");

        base.OnRender(drawingContext);

    }

 

 

}

然后在XAML中创建控件并设置依赖属性:


结果:

DP:Coerce

DP:Changed

FrameworkElement.Initialized

FrameworkElement.MeasureOverride

FrameworkElement.ArrangeOverride

UIElement.OnRender

UIElement.LayoutUpdated

UIElement.LayoutUpdated

FrameworkElement.Loaded

所以,当所有属性初始化后,FrameworkElement.Initialized会运行,接着发生控件就要开始显示了,所以WPF的Measure和Arrange的两步布局步骤就开始了,最后OnRender被调用,控件就显示了。然后UIElement.LayoutUpdated控件此时已经显示,最后Loaded事件发生代表所有预处理项已完成。

你可能感兴趣的:(WPF:UIElement以及FrameworkElement中常见事件的运行顺序)