Monday, October 10, 2011

MVVM Step By Step, part II

In the previous post, we created the initial setup of an MVVM application. We already created a first view, MainView, and a first viewmodel, MainViewModel. Both were hooked up using the DataContext property of the view. What we didn't do yet, was show something in the ContentPresenter on the MainView.

Initially, we want to show all of the customers. In our MVVM app, this will be another view, AllCustomersView, and another viewmodel, AllCustomersViewModel. It will be the responsibility of the MainViewModel to initialize these two. The basics of hooking the view and viewmodel together will be similar to what we did for the MainView and MainViewModel. Lets initialize all this in the constructor of the MainViewModel.

public MainViewModel()
{
    var view = new AllCustomersView();
    var viewmodel = new AllCustomersViewModel();
    view.DataContext = viewmodel;
}

For the AllCustomersView just create a new UserControl in your views folder. For the AllCustomersViewModel, create a new class in your ViewModels folder.

Now that we have this view and viewmodel, we need to be able to show them in the ContentPresenter of the MainView. For this, you will need a property in your MainViewModel to which the MainView ContentPresenter can bind to. We will add this property to the MainViewModel class.

public FrameworkElement ViewToShow { get; set; }

Make sure you assign the view you created in the constructor to this property.

public MainViewModel()
{
    var view = new AllCustomersView();
    var viewmodel = new AllCustomersViewModel();
    view.DataContext = viewmodel;
    ViewToShow = view;
}

Last thing you need to add is the binding in your view.

<ContentPresenter Grid.Column="1" Content="{Binding ViewToShow}" />

Just for testing purposes, you can add a TextBlock with some dummy text in your AllCustomersView and run the application. You should see the content you placed in your AllCustomersView in your application.

That's it, as simple as that. A viewmodel provides properties for your view to bind to. In the next post we will see how we can react to the clicks of the buttons in the MainView.

No comments:

Post a Comment