Why does binding the MainWindow datacontext in XAML fail to act the same as binding in the codebehind with this.datacontext=this?

后端 未结 1 1040
你的背包
你的背包 2021-02-05 14:26

I am trying to use Data binding to bind an ObservableCollection to the ItemsSource of a DataGrid, as I learn about WPF and stuff.

In the code-behind I can set the DataCo

相关标签:
1条回答
  • 2021-02-05 15:07
    <Window.DataContext>
        <local:MainWindow/>
    </Window.DataContext>
    

    is not the same as

    this.DataContext = this;
    

    The first one is creating a new instance of the MainWindow class and assigning that to the DataContext property of the Window, while the second is assigning the very same instance of the Window to its DataContext property.

    In order to achieve that in XAML, you need to use a RelativeSource Binding:

    <Window DataContext="{Binding RelativeSource={RelativeSource Self}}">
    </Window>
    

    Edit:

    The difference in behavior between defining the DataContext in XAML and in code behind is caused by the fact that the XAML is actually parsed when the constructor finishes executing, because the Dispatcher waits for the user code (in the constructor of the Window) to finish before executing its pending operations.

    This causes the actual property values to be different in these different moments, and since there is no INotifyPropertyChanged, WPF has no way of updating the UI to reflect the new values.

    You could implement INotifyPropertyChanged in the Window itself, but I suggest creating a ViewModel for this, as I don't like the fact of mixing INotifyPropertyChanged (which is more of a ViewModel concept) with DependencyObject-derived classes (UI elements).

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