Getting Started

The easiest way to get started with the Simple Mvvm Toolkit is to create a new Visual Studio project using one of the project templates installed by the toolkit.  Each project template creates a fully functioning MVVM application and includes a ReadMe.txt file with instructions for inserting your own classes using the Visual Studio item templates, code snippets and xml snippets. There are project templates for WPF, Silverlight and Windows Phone.  These instructions will build a Silverlight MVVM application.

Watch or download the Getting Started screencast to see a demonstration of following the steps in this Getting Started exercise.

  1. Open Visual Studio 2010, then select File, New Project. 

    mvvm-proj-sl4

    • Under the Silverlight category, select the Mvvm sub-category
    • Select the SimpleMvvmSilverlight project template
    • Name the project Getting Started and click OK
  2. The project already references the SimpleMvvmToolkit assembly.
    • This reference can also be added manually through the Visual Studio Add References dialog.
    • If references for Microsoft.Expression.Interactions and System.Windows.Interactivity are missing,
      you need to install the
      Microsoft Expression Blend SDK.
  3. The project will contain folders for Locators, Models, Services, ViewModels and Views.

    smvvm-sl

    • You can use the files within each of these folders as examples, then simply remove them.
  4. Start by adding a Product class to the Models folder.
    • Derive the class from ModelBase<Product>, which adds data binding capabilities to Product.
    • Use the mvvmprop code snippet to insert two properties:
      ProductId (int)
      ProductName (string)
    • The code snippet will call the base method NotifyPropertyChanged,
      which accepts a lambda expression for the property name.
      • This provides a type-safe way to fire the PropertyChanged event,
        which is necessary for two-way data binding.
    • NOTE: Code snippets have been around for quite a while and make it easier to write boilerplate code.  Code snippets exist for many C# constructs, such as for, foreach, switch, etc.  After inserting the code snippet, it acts like a form where you type a value and hit tab to go to the next field. You can create your own code snippets using a tool such as Snippet Designer, which you can install by going to Tools / Extensions Manager and searching for Snippet Designer in the Online Gallery.

    public class Product : ModelBase<Product>
    {
        private int productId;
        public int ProductId
        {
            get { return productId; }
            set
            {
                productId = value;
                NotifyPropertyChanged(m => m.ProductId);
            }
        }
    
        private string productName;
        public string ProductName
        {
            get { return productName; }
            set
            {
                productName = value;
                NotifyPropertyChanged(m => m.ProductName);
            }
        }
    }
  5. Next add an IProductServiceAgent interface to the Services folder.

    • Include a LoadProducts method that returns a List<Product>
    public interface IProductServiceAgent
    {
        List<Product> LoadProducts();
    }
  6. Add a MockProductServiceAgent class that implements IProductServiceAgent.
    • Flesh out the LoadProducts method by creating a new List<Product> with a few products in it.
    public class MockProductServiceAgent : IProductServiceAgent
    {
        public List<Product> LoadProducts()
        {
            return new List<Product>
            {
                new Product { ProductId = 1, ProductName = "Chai" },
                new Product { ProductId = 2, ProductName = "Capuccino" },
                new Product { ProductId = 3, ProductName = "Latte" },
                new Product { ProductId = 4, ProductName = "Americano" },
                new Product { ProductId = 5, ProductName = "Machiato" }
            };
        }
    }
  7. Next we’re going to create a ProductListViewModel.  But instead of just adding a class with this name to the project, we’ll use one of the Visual Studio item templates that ship with the Simple Mvvm Toolkit!
    • Right-click the ViewModels folder and select Add New Item.
    • Expand the Silverlight category on the left to select the Mvvm category.
    • Select SimpleMvvmViewModel, enter ProductListViewModel.cs for the name, then click the Add button.

      mvvm-items-sl4

    • What you get is a class which extends ViewModelBase<TViewModel>
    • Replace the /* IXxxServiceAgent */ comment in the serviceAgent field with IProductServiceAgent.
    • Replace the /* IXxxServiceAgent */ comment in the constructor with IProductServiceAgent.
    public class ProductListViewModel : ViewModelBase<ProductListViewModel>
    {
        // Add a member for IProductServiceAgent
        private IProductServiceAgent serviceAgent;
    
        // Default ctor
        public ProductListViewModel() { }
    
        // ctor that accepts IProductServiceAgent
        public ProductListViewModel(IProductServiceAgent serviceAgent)
        {
            this.serviceAgent = serviceAgent;
        }
    • Using the mvvmprop code snippet add a Products property to the ProductListViewModel.
      • Make the property an ObservableCollection<Product>
    • Add a LoadProducts method.
      • Call LoadProducts on serviceAgent and pass the result to the ctor of an ObservableCollection<Product>
      • Set the Products property to the ObservableCollection<Product>
    private ObservableCollection<Product> products;
    public ObservableCollection<Product> Products
    {
        get { return products; }
        set
        {
            products = value;
            NotifyPropertyChanged(vm => vm.Products);
        }
    }
    
    public void LoadProducts()
    {
        var products = serviceAgent.LoadProducts();
        Products = new ObservableCollection<Product>(products);
    }
  8. Open the ViewModelLocator.cs file, which resides in the Locators folder.
    • Use the mvvmlocator code snippet to add a property that creates the ProductListViewModel on demand.
      • Set serviceAgent to a new MockProductServiceAgent
    public class ViewModelLocator
    {
        // Create ProductListViewModel on demand
        public ProductListViewModel ProductListViewModel
        {
            get
            {
                IProductServiceAgent serviceAgent = new MockProductServiceAgent();
                return new ProductListViewModel(serviceAgent);
            }
        }
    }
  9. Now that you’ve created a model and view-model, it’s time to create a view.
    • Right-click on the GettingStarted project to add a new Silverlight User Control named ProductListView.xaml
    • Move ProductListView.xaml to the Views folder

      Add New Item - HelloSimpleMvvmSL

    • Add two rows to the grid, with a Button in the first row and a DataGrid in the second row.
    • Right-click on ProductListViewModel.xaml in the solution explorer and select Open With…
      • Then choose the XML (Text) Editor and click OK (click Yes on the confirm dialog).

      Open With - ProductListView.xaml

    • Place the cursor before the > symbol in the UserControl element, then right-click and select Insert Snippet.
      • Select My XML Snippets / SimpleMvvm / mvvmxmlns, which inserts the blend namespaces
      • Select My XML Snippets / SimpleMvvm / mvvmcontext, and bind the DataContext to the Locator’s ProductListViewModel property.
    • Lastly, provide a closing </Button> element and insert a blend event trigger to call the LoadProducts method on the Click event.
      • Select My XML Snippets / SimpleMvvm / mvvmcommand, and type LoadProducts for the MethodName.
    • While you’re at it, go ahead and bind the ItemsSource property of the DataGrid with Path=Products
    • Double-click on ProductListView.xaml in the solution explorer to re-open the file in the designer. The XAML should look like this:
    <UserControl x:Class="HelloSimpleMvvmSL.ProductListView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
        mc:Ignorable="d"
        d:DesignHeight="300" d:DesignWidth="400"
        DataContext="{Binding Source={StaticResource Locator}, Path=ProductListViewModel}"
        >
        
        <Grid x:Name="LayoutRoot" Background="White">
            <Grid.RowDefinitions>
                <RowDefinition Height="46*" />
                <RowDefinition Height="254*" />
            </Grid.RowDefinitions>
          <Button Content="Load Products" Height="23" HorizontalAlignment="Left"
                  Margin="12,12,0,0" Name="loadProductsButton"
                  VerticalAlignment="Top"Width="95">
            <i:Interaction.Triggers>
              <i:EventTrigger EventName="Click">
                <ei:CallMethodAction
                        TargetObject="{Binding}"
                        MethodName="LoadProducts"/>
              </i:EventTrigger>
            </i:Interaction.Triggers>
          </Button>
            <sdk:DataGrid AutoGenerateColumns="True" Grid.Row="1" Height="214" 
                HorizontalAlignment="Left" Margin="12,14,0,0" Name="dataGrid1"
                VerticalAlignment="Top" Width="376"
                ItemsSource="{Binding Path=Products, Mode=TwoWay}" />
        </Grid>
    </UserControl>
    
  10. That’s all there is to it!  Just set the content of MainPage.xaml to show the ProductListView, then press F5 to run the application.
    • Clicking on the Load Products button will display a list of products created by the MockProductServiceAgent and bound to the Products property of the ProductListViewModel.
    <UserControl x:Class="HelloSimpleMvvmSL.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        d:DesignHeight="300" d:DesignWidth="400">
    
        <Grid x:Name="LayoutRoot" Background="White">
            <my:ProductListView xmlns:my="clr-namespace:HelloSimpleMvvmSL"/>
        </Grid>
        
    </UserControl>
    

    WindowClipping

This Getting Started guide has walked you through the steps of building an MVVM Silverlight application using the Simple MVVM Toolkit.  This includes using Visual Studio project and item templates, together with code and xml snippets, to produce service agents, models, view-models, and views.  View-models are served up by a view-model locator, which creates a service agent and passes it to the ctor of the view-model.  The DataContext of the view is set to a view-model property on the locator so that elements on the view can be bound to properties on the view-model.

In this exercise you used a mock service agent to create dummy model classes. To see how to connect this project to a WCF service for retrieving entities from a database, open projects in Samples\SimpleMvvm-Main and follow steps contained in the ReadMe files.  Part 1 includes more information on using the toolkit, for example, concerning modal dialogs.  Part 2 takes it a step further with navigation, messaging and async operations.  Part 3 ports the solution to WCF RIA Services.

Last edited Sep 10, 2011 at 10:01 PM by tonysneed, version 8

Comments

jtorkelson Aug 11 at 6:39 PM 
Hello, I set up a WPF project and have been following the instructions, however I'm to the point now where I'm supposed to insert a snippet into the ProductListView.xaml using the XML editor, however the snippet doesn't show up. How do I find the My XML Snippets / SimpleMvvm / mvvmxmlns snippet? Thanks!

anhtuanis Jul 30 at 6:38 PM 
Sory, I eror "<my:ProductListView xmlns:my="clr-namespace:SVandMVVMDemo"/>"
help me

jlebrech Oct 17, 2011 at 4:04 PM 
Hi, I'm trying to adapt this tutorial for Windows Phone. I can't get the trigger to work. How do I LoadProducts as soon as the page has loaded? And how would I use those in a ListBox. thanks.

hjyanghj Oct 15, 2011 at 1:00 PM 
Nice documentation.
It is nice to have included: how/when to insert item template and code/xaml snippet.
Thanks a lot.

tonysneed Jun 1, 2011 at 11:06 PM 
@Dolemike: Glad you figured it out. :-) I will need to do a Getting Started for WP7.

Dolemike Jun 1, 2011 at 9:52 PM 
I found the answer LOL. I had wired up some command stuff from MVVM Light to get it all working and then as I read more documentation on your site I found that you already had it all baked in. I am just getting started, but so far I am finding this more simple to use. It would be nice if you updated this getting started guide to include the same WP7 caveats you have in the readme.txt. Thank you for documenting this so well. With MVVM Light I had to search all over the place to find an answer. So far everything I have been doing wrong I found the answer to on your site.

Dolemike Jun 1, 2011 at 10:05 AM 
Your getting started guide for WP7 doesn't work. Interactions don't work as I guess I have to download an action pack and:

Products = new ObservableCollection<Product>(products); <----That ctor doesn't exist in SL3.

tonysneed Apr 22, 2011 at 3:28 PM 
@Marty: I have updated this Getting Started guide to use the new Visual Studio project template I added to the toolkit, which supplies all the required references (but you still need to have installed the Blend SDK). Just download and run the installer. The Getting Started Screencast (available from the project Home page) will guide you through these steps.

mltguzzi Feb 24, 2011 at 4:50 PM 
Tony,

I really appreciate the toolkit. I'm going through the process of getting up to speed with it now. I followed your instructions above and found that there were some missing references. Your completed version of the SimpleMvvm-GettingStarted project had these two additional references;

System.Windows.Controls.Data.Input
System.ComponentModel.DataAnnotations

It turns out System.Windows.Controls.Data.Input is required in order for the sdk namespace to be recognized, which threw me at first.

When I got it running mine didn't look like yours. I noticed that you had added a width and height to the Grid in the CustomerView user control. You have it in the code above, but I missed it, since it wasn't highlighted.

Thanks again for the toolkit. I've been trying to break into MVVM for the last few days and wasn't having much luck at finding examples or documentation in other places.

Marty