The View is the "V" in MVVM. This is your user interface. You can use the Visual Studio drag-and-drop designer, but most developers eventually end up coding the raw XAML - an experience similar to writing HTML.
Here is the XAML of a simple view to allow editing of a Customer
model. Rather than create a new view, this can just be pasted into a WPF project's MainWindow.xaml
file, in-between the <Window ...>
and </Window>
tags:-
<StackPanel Orientation="Vertical"
VerticalAlignment="Top"
Margin="20">
<Label Content="Forename"/>
<TextBox Text="{Binding CustomerToEdit.Forename}"/>
<Label Content="Surname"/>
<TextBox Text="{Binding CustomerToEdit.Surname}"/>
<Button Content="Apply Changes"
Command="{Binding ApplyChangesCommand}" />
</StackPanel>
This code creates a simple data entry form consisting of two TextBox
es - one for the customer forename, and one for the surname. There is a Label
above each TextBox
, and an "Apply" Button
at the bottom of the form.
Locate the first TextBox
and look at it's Text
property:
Text="{Binding CustomerToEdit.Forename}"
Rather than setting the TextBox
's text to a fixed value, this special curly brace syntax is instead binding the text to the "path" CustomerToEdit.Forename
. What's this path relative to? It's the view's "data context" - in this case, our view-model. The binding path, as you may be able to figure out, is the view-model's CustomerToEdit
property, which is of type Customer
that in turn exposes a property called Forename
- hence the "dotted" path notation.
Similarly, if you look at the Button
's XAML, it has a Command
that is bound to the ApplyChangesCommand
property of the view-model. That's all that's needed to wire up a button to the VM's command.
The DataContext
So how do you set the view-model to be the view's data context? One way is to set it in the view's "code-behind". Press F7 to see this code file, and add a line to the existing constructor to create an instance of the view-model and assign it to the window's DataContext
property. It should end up looking like this:
public MainWindow()
{
InitializeComponent();
// Our new line:-
DataContext = new CustomerEditViewModel();
}
In real world systems, other approaches are often used to create the view model, such as dependency injection or MVVM frameworks.