Click here to Skip to main content
15,889,216 members
Articles / All Topics

Extend ViewModelLocator to be a Bit More Dynamic

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
27 Dec 2010CPOL2 min read 11.6K   3  
Using attributes and reflection to bind the viewmodel to the view

I've been using MVVM Light in my Windows Phone development. It's lightweight, has all the base functionality I need and seems pretty solid.

One pattern that MVVM Light uses is a static ViewModelLocator class that holds all of the main/root view models in the application. You declare it as a data source in the app.xaml:

XML
<vm:ViewModelLocator d:isdatasource="True" x:key="Locator"/>

Then in the page XAML, you can do:

XML
DataContext="{Binding Main, Source={StaticResource Locator}}"

This is great when there is basically a 1:1 mapping between the page and the contents of each view model. What it's not so good at dealing with is the situation where you want the same page to bind to multiple view models that are structurally equivalent but have different data contents.

Take for instance an RSS viewer (which coincidentally enough I'm working on at the moment). You might have a feed that represents articles from a website and another feed that is discussion posts from the same website. Each feed is further broken down into topic channels. So if we wanted to display each feed as a page, with each topic as a Pivot Item on that page, we could distill the page XAML down to:

XML
<controls:Pivot Title="{Binding Name}" 
   ItemsSource="{Binding Topics}" 
   ItemTemplate="{StaticResource RssTopicTemplate}"/>

Now if the ViewModel is statically linked to the page (as above), we need to parametrize the ViewModel as the user navigates from articles to discussions and back. It can be made to work, but it violates the Single Responsibility Principle and I just don't like it.

So rather than parametrizing the ViewModel, how about we parametrize the page? Let's declare the linkage between ViewModel in page on the ViewModel. We'll declare an attribute that specifies the linkage and allows a parameter to be passed the page in the form of a query string.

C#
[Page("/RssPage.xaml?vm=ArticlesStatic")]
public class ArticlesViewModel : ViewModelBase

...

[Page("/RssPage.xaml?vm=ForumsStatic")]
public class ForumsViewModel : ViewModelBase

In this app, the set of navigable items are collections of viewmodels that are displayed in ListBoxes wherein each ViewModel can be selected and navigated to:

C#
public class ContentsViewModel : ViewModelBase
{
   public ObservableCollection<ViewModelBase> Contents 
             { get; private set; }
   public RelayCommand<object> SelectViewModel 
             { get; private set; }

   private void Select(object vm)
   {
      if (vm != null)
      {
         var page = vm.GetType().GetAttribute<PageAttribute>();
         Navigate(page.Page);
      }
   }
}

Then we need a wee bit of code in the page codebehind:

C#
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    if (NavigationContext.QueryString.ContainsKey("vm"))
    {
        string key = NavigationContext.QueryString["vm"];
        DataContext = ViewModelLocator.FindViewModel(key);
    }
    base.OnNavigatedTo(e);
}

where FindViewModel is a method added to the ViewModelLocator that returns the correct ViewModel using reflection:

C#
public static object FindViewModel(string key)
{
    var prop = typeof(ViewModelLocator).GetProperty(key, 
              BindingFlags.Public | BindingFlags.Static);

    return prop.GetValue(null, null);
}

I find that moving the linkage between View and ViewModel onto the ViewModel gives us the flexibility to reuse the same UI to display the contents of multiple, structurally equivalent ViewModels, while still maintaining a loose coupling between those two layers.

This article was originally posted at http://spookycoding.blogspot.com/feeds/posts/default

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader Starkey Laboratories
United States United States
The first computer program I ever wrote was in BASIC on a TRS-80 Model I and it looked something like:
10 PRINT "Don is cool"
20 GOTO 10

It only went downhill from there.

Hey look, I've got a blog

Comments and Discussions

 
-- There are no messages in this forum --