Mark Featherston
Mark Featherston

Reputation: 33

What is the preferred way to connect viewmodels to their views?

In the past while working with MVVM I've created every View as a DataTemplate to it's corresponding viewmodel to handle connecting them. I just started using MVVM Light, and noticed they have the ViewModelLocator. Several other toolkits I've looked at include some variation of this, but what benefit does this bring over using DataTemplate?

Which is the best practice for connecting your Views and ViewModels?

Upvotes: 3

Views: 4889

Answers (2)

gideon
gideon

Reputation: 19465

The way I see it:

  1. You have one nice place for all the ViewModels.
  2. There is a nice cleanup mechanism MVVMLight Provides.
  3. You can connect your ViewModels in your markup statically. --- This could sometimes be a problem if you don't realize that your ViewModel is instantiated and set to the DataContext as soon as you create an instance of the UI.

For (3) (How to use the ViewModelLocator) :

  1. Make sure you have the snippets installed.
  2. Open ViewModelLocator.cs and type mvvmlocatorproperty. Select it in the intellisense and double TAB for the snippet to work. Change it to the appropriate property.
  3. In your xaml you will use it like this:

    <Window.DataContext>
        <Binding Path="HomePage" Source="{StaticResource Locator}"/>
    </Window.DataContext>
    

For this property:

    public HomePageViewModel HomePage
    {
        get
        {
            return HomePageStatic;
        }
    }

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564433

There are two different approaches, and not one "right way".

The approach that a ViewModelLocator or similar helps with is a "View-First" approach to developing MVVM. By this, it means you start with your View in the designer, and then build the ViewModel to match. Logically, Views often create other Views, and the ViewModel is typically loaded via some form of locator and populated for a given View. Messaging or services are used to hook appropriate models into the newly generated ViewModels.

This has the advantage of being a bit easier to design visually, especially when working with Blend.

The other approach is to work "ViewModel-First". By this, you generate your ViewModels, and then use DataTemplates to have the View populate. ViewModels will compose/create other VMs, directly setting the appropriate Model. This is typically (IMO) much, much cleaner from a programmer's perspective, as things just work directly. However, it's typically more difficult to design and work with from a designer's point of view, as design-time data is more difficult to generate, etc.

Both approaches are perfectly valid, and have strong advantages and disadvantages. Different MVVM purists tend to prefer one approach over the other for various reasons - typically whether they're approaching this from a code cleanliness point of view or a designer point of view.

Upvotes: 6

Related Questions