Need help setting up MVVM Light ViewModelLocator

2019-07-19 08:22发布

问题:

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.

回答1:

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}}"