MVVM指示灯无法在Windows 10 Universal应用程序中运行

我试图在我们的Windows 10 Universal应用程序中使用MVVMLight,但似乎它完全无法工作.我见过这个blog

Nuget downloaded and added a reference to the MVVM Light assemblies

Nuget also added the ViewModelLocator in the Application.Resources.

在Application.Resources中看不到Locator

您需要手动创建ViewModelLocator,请按照以下步骤操作:

>创建一个新的Windows 10 Universal应用程序,例如:MVVMLightUWPApp1
>使用NuGet Package Manager添加对MVVMLight的引用
>为您的UWP应用添加一个文件夹,例如:ViewModel
>在ViewModel文件夹下,添加两个类:MainViewModel和ViewModelLocator
enter image description here

在MainViewModel.cs中:

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

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

>在App.xaml中:

<Application.Resources>
   <vm:ViewModelLocator xmlns:vm="using:MVVMLightUWPApp1.ViewModel"
                               x:Key="Locator" />
</Application.Resources>

>在View中,将DataContext设置如下:

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

>现在,您可以设置与VM的绑定,例如:

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

好好享受:)

翻译自:https://stackoverflow.com/questions/32186295/mvvm-light-cant-work-in-windows-10-universal-app

转载注明原文:MVVM指示灯无法在Windows 10 Universal应用程序中运行