MVVM light can't work in Windows 10 Universal

2019-03-09 13:47发布

I tried to use MVVMLight in our Windows 10 Universal app, but it seems like that it totally can't work. I've seen this blog

Nuget downloaded and added a reference to the MVVM Light assemblies

Nuget also added the ViewModelLocator in the Application.Resources.

Can't see the Locator in Application.Resources

1条回答
Anthone
2楼-- · 2019-03-09 14:25

You need to create the ViewModelLocator manually, please follow these steps:

  1. Create a new Windows 10 Universal app, for example: MVVMLightUWPApp1
  2. Add reference to MVVMLight using NuGet Package Manager
  3. Add a folder for your UWP app, for example: ViewModel
  4. Under the ViewModel folder, add two classes: MainViewModel and ViewModelLocator enter image description here

In MainViewModel.cs:

namespace MVVMLightUWPApp1.ViewModel
{
    public class MainViewModel
    {
        public string MSG { get; set; }
        public MainViewModel()
        {
            MSG = "Test Message";
        }
    }
}

In ViewModelLocator.cs:

namespace MVVMLightUWPApp1.ViewModel
{
    public class ViewModelLocator
    {/// <summary>
     /// Initializes a new instance of the ViewModelLocator class.
     /// </summary>
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            ////if (ViewModelBase.IsInDesignModeStatic)
            ////{
            ////    // Create design time view services and models
            ////    SimpleIoc.Default.Register<IDataService, DesignDataService>();
            ////}
            ////else
            ////{
            ////    // Create run time view services and models
            ////    SimpleIoc.Default.Register<IDataService, DataService>();
            ////}

            SimpleIoc.Default.Register<MainViewModel>();
        }

        public MainViewModel Main
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }

        public static void Cleanup()
        {
            // TODO Clear the ViewModels
        }
    }
}
  1. In App.xaml:

    <Application.Resources>
       <vm:ViewModelLocator xmlns:vm="using:MVVMLightUWPApp1.ViewModel"
                                   x:Key="Locator" />
    </Application.Resources>
    
  2. In the View, set DataContext as below:

    DataContext="{Binding Main, Source={StaticResource Locator}}"
    
  3. Now, you can set binding to VM, for example:

    <TextBlock Text="{Binding MSG}" FontSize="50" />
    

Enjoy it:)

查看更多
登录 后发表回答