Wednesday, 21 May 2014

Six ways to instantiate a ViewModel in MVVM

There are many ways you can attach your ViewModel to your View in WPF; here are some of the ways.

Direct reference to the ViewModel

This is the simplest method.

<UserControl xmlns:vm="clr-namespace:MyWPFUserControls">

Use a CollectionViewSource

    <CollectionViewSource x:Key="categoryViewSource" d:DesignSource="{d:DesignInstancemy:Category, CreateList=True}" />
<Grid DataContext="{StaticResource categoryViewSource}">

private void Window_Loaded(object sender, RoutedEventArgs e)
        System.Windows.Data.CollectionViewSource categoryViewSource =

        // Load is an extension method on IQueryable, defined in the System.Data.Entity namespace.
        // This method enumerates the results of the query, much like ToList but without creating a list.
        // When used with Linq to Entities this method creates the entity instances and adds to the context.
        _context.Categories.Load(); // Load is defined in the System.Data.Entity namespace.     

        // After the data is loaded call the DbSet<T>.Local property to use the DbSet<T> as a binding source.
        categoryViewSource.Source = _context.Categories.Local;      


CollectionViewSource – more simple version

        <CollectionViewSource x:Key="MainDataSource"/>
    <Grid DataContext="{Binding Source={StaticResource MainDataSource}}">
var collectionView = (CollectionViewSource)Resources["MainDataSource"];
collectionView.Source = entitiesContext.ArCustomers;

Call a method

Note the "Class" reference on the second line.

   Title="WPF DataGrid CRUD Sample"
   Icon="/DataGridSample;component/dotbay.png" >
   ItemsSource="{Binding Source={x:Static local:FormulaOneDriver.GetAll}}"


Call a method in an ObjectDataProvider

<Window ...>

        <!-- create an instance of our DataProvider class -->
        <ObjectDataProvider x:Key="CustomerDataProvider"
            ObjectType="{x:Type local:CustomerDataProvider}"/>
        <!-- define the method which is invoked to obtain our data -->
        <ObjectDataProvider x:Key="Customers"
          ObjectInstance="{StaticResource CustomerDataProvider}"

    <DockPanel DataContext="{Binding Source={StaticResource Customers}}">
        <dg:DataGrid ItemsSource="{Binding}" Name="dataGrid"/>

public class CustomerDataProvider
    private CustomersTableAdapter adapter;

    private NorthwindDataSet dataset;

    public CustomerDataProvider()
        dataset = new NorthwindDataSet();
        adapter = new CustomersTableAdapter();

    public DataView GetCustomers()
        return dataset.Customers.DefaultView;



You can initialize the View and View Model by using an OnStartup() override added to App.xaml.cs. The View is bound to the View Model by setting the View Model as the data context for the View:

protected override void OnStartup(StartupEventArgs e)

    var mainWindow = new MainWindow();
    var mainWindowViewModel = new MainWindowViewModel();
    mainWindow.DataContext = mainWindowViewModel;



No comments:

Post a Comment