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
<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).