问题
How can you create a binding between a ViewModel and a View?
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}}"
I can't even click in the Properties of the View and then create DataContext binding.
回答1:
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
.
Here's an example how I used it in a recent UWP project.
In App.xaml
private ViewModels.ViewModelLocator Locator => Application.Current.Resources["Locator"] as ViewModels.ViewModelLocator;
In MainPage.xaml
DataContext="{Binding MainViewModel, Source={StaticResource Locator}}">
In MainPage.cs
private MainViewModel ViewModel
{
get { return DataContext as MainViewModel; }
}
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));
}
}
}
回答2:
Ok I found it out:
You need to add this in App.xaml:
private static ViewModelLocator _locator;
public static ViewModelLocator Locator => _locator ?? (_locator = new ViewModelLocator());
And then in the View.xaml:
this.DataContext = App.Locator.MainViewModel;
来源:https://stackoverflow.com/questions/52457162/mvvmlightlibsstd10-and-uwp