So far we've build a model, a view model, and unit tests. Now we finally want the user to access the application. To do so, we create a Silverlight application and data bind to the view model.

Add a new Silverlight Application project to the solution. Call the project "Lesson.Client". This new project should reference both Lesson.Model and Lesson.ViewModel. Add a NuGet reference. Search for "Correspondence.Silverlight.App". Follow the instructions in the Readme.txt file to set up the view model locator.

Create a UserControl with which the user can access the log on capabilities. Call it "LogOnControl". This control will need a TextBox data bound to UserName and a Button data bound to the LogOn command.
<UserControl x:Class="Lesson.Client.LogOnControl"
    <StackPanel Orientation="Horizontal">
        <TextBox Text="{Binding UserName}" Width="120"/>
        <Button Command="{Binding LogOn}">Log On</Button>
Add this user control to the main window. Data bind the data context of the control to a property called "MachineVM".
    DataContext="{Binding Main, Source={StaticResource Locator}}">
        <local:LogOnControl DockPanel.Dock="Top" DataContext="{Binding MachineVM}"/>
        <TextBox />
The package created a view model for the main window. Let's add a property called MachineVM that gives us a MachineViewModel.
public class MainViewModel
    public MachineViewModel MachineVM
            return new MachineViewModel(_machine, new MachineNavigationModel());
The view model locator that the package created wraps the main view model so it can be data bound.
public object Main
    get { return ForView.Wrap(_main); }
The ForView.Wrap is very important. It is creating a wrapper around the view model that implements INotifyPropertyChanged for you. This comes from Update Controls, which automatically detects dependencies. It discovers which properties of the view model depend upon which properties of the data model, and fires the right events when those properties change.

Data binding in Update Controls is automatic. All you have to do is call ForView.Wrap when you set the main DataContext. All properties of that view model are automatically wrapped. The wrapper is transitive. Because the MainViewModel is wrapped, the MachineViewModel will also be wrapped.

Next: Practice 2: Create a view model

Last edited May 15, 2011 at 4:53 AM by MichaelLPerry1971, version 5


No comments yet.