我尝试在我们的Windows 10 Universal应用中使用 MVVMLight ,但似乎它完全无法正常工作。我已经看到了blog
Nuget已下载并添加了对MVVM Light程序集的引用
Nuget还在Application.Resources中添加了ViewModelLocator。
无法在Application.Resources
答案 0 :(得分:18)
您需要手动创建ViewModelLocator,请按以下步骤操作:
在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>
在视图中,将DataContext设置如下:
DataContext="{Binding Main, Source={StaticResource Locator}}"
现在,您可以设置与VM的绑定,例如:
<TextBlock Text="{Binding MSG}" FontSize="50" />
享受它:)