MvvmLightLibsStd10和UWP [英] MvvmLightLibsStd10 and UWP
问题描述
如何在ViewModel和View之间创建绑定?
How can you create a binding between a ViewModel and a View?
过去,在App.xaml中创建了一个Locater,然后在视图上显示以下内容:
In the past there was a Locater created in App.xaml and then on the view you had this:
DataContext="{Binding MainViewModel, Source={StaticResource ViewModelLLocator}}"
我什至不能单击视图"的属性",然后创建DataContext绑定.
I can't even click in the Properties of the View and then create DataContext binding.
推荐答案
在MVVM light的最新版本中,由于ViewModelLocator
依赖于Microsoft.Practices.ServiceLocation
并且前者不符合.NET Standard,因此它们更改了ViewModelLocator
的工作方式.现在,它应该使用GalaSoft.MvvmLight.Ioc
使用SimpleIoc
定位ViewModel
.
In recent versions of MVVM light they changed how ViewModelLocator
works due to it taking a dependency on Microsoft.Practices.ServiceLocation
and the former not being .NET Standard compliant. It now should use GalaSoft.MvvmLight.Ioc
to locate the ViewModel
using SimpleIoc
.
这是我在最近的UWP项目中如何使用它的一个示例.
Here's an example how I used it in a recent UWP project.
在App.xaml中
private ViewModels.ViewModelLocator Locator => Application.Current.Resources["Locator"] as ViewModels.ViewModelLocator;
在MainPage.xaml中
In MainPage.xaml
DataContext="{Binding MainViewModel, Source={StaticResource Locator}}">
在MainPage.cs
In MainPage.cs
private MainViewModel ViewModel
{
get { return DataContext as MainViewModel; }
}
在ViewModelLocator.cs
In ViewModelLocator.cs
namespace YourNamespace.ViewModels
{
public class ViewModelLocator
{
public ViewModelLocator()
{
Register<MainViewModel, MainPage>();
}
public MainViewModel MainViewModel => SimpleIoc.Default.GetInstance<MainViewModel>();
public void Register<VM, V>()
where VM : class
{
SimpleIoc.Default.Register<VM>();
NavigationService.Configure(typeof(VM).FullName, typeof(V));
}
}
}
这篇关于MvvmLightLibsStd10和UWP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!