MvvmLightLibsStd10 and UWP

空扰寡人 提交于 2020-01-06 05:06:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!