2

As the title says, I need some help setting up my ViewModelLocator. It's a Windows Phone 7 app that uses the Galasoft MVVM Light Toolkit.

I have a second page in my app which I need to wire up to the view model, but after looking strenuously on the internet for the past hour, haven't really been able to find a simple example of adding ViewModels to the locator. All I need is a code example of what I need to add to the locator and whereabouts to add it.

Thanks to anyone who can help me with this.

Tom
  • 1,275
  • 1
  • 18
  • 51

1 Answers1

3

This is my ViewModelLocator:

public class ViewModelLocator
{
    public MainPageViewModel MainPage
    {
        get { return new MainPageViewModel(); }
    }
}

This is a piece of my App.xaml:

<Application.Resources>
    <vm:ViewModelLocator
        x:Key="ViewModelLocator" />
</Application.Resources>

This is a piece of my page xaml:

DataContext="{Binding MainPage, Source={StaticResource ViewModelLocator}}"
Filip Skakun
  • 31,624
  • 6
  • 74
  • 100
  • I would expand on this slightly as you should have a private member to contain the instance of the "MainViewModel" within the locator, this saves new instances of the view model being created every time a user navigates to a page that consumes the view model. as you are using MVVMLight, this gives you a template ViewModel Locator (version 4 also includes a simpleIOC function to better control data flow) when you create a new project using the MVVM Project template. – Darkside Nov 10 '11 at 14:30
  • You don't need to save it unless you want to reuse it in different views. The phone has limited memory so if you save all your view models - you are toast. The main view model as in the one for the main page - will only be destroyed when you exit the app or get tombstoned which you won't prevent anyway by saving it in a field. – Filip Skakun Nov 10 '11 at 17:59