The order of Dependency Property and DataContext assignment

  Kiến thức lập trình

From my testing, it seems that the DataContext seems to be always assigned first before the assignment of Dependency Property, if I only set the DataContext and the Dependency Property once via XAML ( see the example below).

But is this always true? Is there a C# language spec that says– no, guarantees — this? I need this because my program depends precisely on this behavior.

Here’s the code that I can use to illustrate this point:

View Models

public class MainWindowVM
{
    public SimpleTextBoxVM SimpleText => new SimpleTextBoxVM();
}
public class SimpleTextBoxVM
{
}

public class Updater
{
}

UI

public class Updater
{
}

public partial class SimpleTextBoxExt : UserControl
{
    public SimpleTextBoxExt()
    {
        InitializeComponent();
        DataContextChanged += OnDataContextChanged;
    }

    private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue != null)
        {
            Console.WriteLine("DataContext Assigned."); //this seems always executed first

        }
    }

    public static readonly DependencyProperty FractionalNumberProperty = DependencyProperty.Register(
        nameof(FractionalNumber), typeof(Updater), typeof(SimpleTextBoxExt), new PropertyMetadata(default(Updater), PropertyChangedCallback));

    private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is SimpleTextBoxExt simpleTextBox)
        {
            Console.WriteLine("Dependency property set"); //this seems always executed later
        }
    }



    public Updater FractionalNumber
    {
        get { return (Updater)GetValue(FractionalNumberProperty); }
        set { SetValue(FractionalNumberProperty, value); }
    }
}

<Window x:Class="DependencyPropertiesUI.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DependencyPropertiesUI"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
   <Window.DataContext>
       <local:MainWindowVM/>
   </Window.DataContext>
    <local:SimpleTextBoxExt DataContext="{Binding SimpleText}">
        <local:SimpleTextBoxExt.FractionalNumber>
            <local:Updater/>
        </local:SimpleTextBoxExt.FractionalNumber>
    </local:SimpleTextBoxExt>
</Window>

2

LEAVE A COMMENT