MVVM light 无法在 Windows 10 通用应用程序中工作

MVVM light can't work in Windows 10 Universal app

我尝试在我们的 Windows 10 通用应用程序中使用 MVVMLight,但它似乎完全无法工作。我看过这个 blog

Nuget downloaded and added a reference to the MVVM Light assemblies

Nuget also added the ViewModelLocator in the Application.Resources.

Application.Resources

中看不到定位器

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

  1. 创建一个新的Windows 10 通用应用程序,例如:MVVMLightUWPApp1
  2. 使用 NuGet 包管理器
  3. 添加对 MVVMLight 的引用
  4. 为您的 UWP 应用添加一个文件夹,例如:ViewModel
  5. ViewModel文件夹下,添加两个类:MainViewModelViewModelLocator

在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
        }
    }
}
  1. 在App.xaml中:

    <Application.Resources>
       <vm:ViewModelLocator xmlns:vm="using:MVVMLightUWPApp1.ViewModel"
                                   x:Key="Locator" />
    </Application.Resources>
    
  2. 在视图中,设置 DataContext 如下:

    DataContext="{Binding Main, Source={StaticResource Locator}}"
    
  3. 现在可以设置绑定到VM,例如:

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

尽情享受吧:)