philologon
philologon

Reputation: 2105

Seeking a better understanding of databinding to a ViewModel

I am still on the steep part of the learning curve of WPF and the MVVM pattern. Part of my approach is to "undertand how things work on a starship" (so to speak). That is, for my learning style, a little under-the-hood understanding helps me a lot.

So it looks to me like the action that I take in code which causes my ViewModel to be instantiated is declare the DataContext in XAML. Can someone confirm this for me or correct it? In other words, in this XAML code snippet,

<Window x:Class="MainRM21WPFapp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mainVM="clr-namespace:MainRM21WPFapp.ViewModels"
    Title="RM21 Demonstration Application" Height="500" Width="700">
<Window.DataContext>
    <mainVM:MainWindowVM />
</Window.DataContext>
<Grid>
...
</Grid>

it is this:

<Window.DataContext>
    <mainVM:MainWindowVM />
</Window.DataContext>

which causes the CLR to create a new instance of my class MainWindowVM. Do I understand it correctly?

Upvotes: 0

Views: 67

Answers (1)

akton
akton

Reputation: 14386

That is correct. The XAML above instructs WPF to instantiate an instance of the class MainWindowVM and assign it to the DataContext property. You can also create it an manually assign it to the DataContext property in the code behind if you need to call a constructor that takes parameters, for example, but the XAML solution is just as effective in your case.

Setting the DataContext property allows data binding to occur. For example, if you have a TextBlock control, you can bind it to property X with:

<TextBlock Text="{Binding Path=X}" />

Make sure your view model class implements the INotifyPropertyChanged interface and fires the PropertyChanged event to inform the view (your Window class) when properties change so it can update any data bindings. In the example above, this ensures whenever the value of property X changes in the view model, WPF knows to automatically update the TextBlock.

Upvotes: 2

Related Questions