user7849697
user7849697

Reputation: 597

MvvmLightLibsStd10 and UWP

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.

Upvotes: 0

Views: 778

Answers (2)

fourwhey
fourwhey

Reputation: 530

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));
        }
    }
}

Upvotes: 1

user7849697
user7849697

Reputation: 597

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;

Upvotes: 0

Related Questions