I tried to use MVVMLight in our Windows 10 Universal app, but it seems like that it totally can't work. I've seen this blog
Nuget downloaded and added a reference to the MVVM Light assemblies
Nuget also added the ViewModelLocator in the Application.Resources.
Can't see the Locator in Application.Resources
You need to create the ViewModelLocator manually, please follow these steps:
- Create a new Windows 10 Universal app, for example: MVVMLightUWPApp1
- Add reference to MVVMLight using NuGet Package Manager
- Add a folder for your UWP app, for example: ViewModel
- Under the ViewModel folder, add two classes: MainViewModel and ViewModelLocator
In MainViewModel.cs:
namespace MVVMLightUWPApp1.ViewModel
{
public class MainViewModel
{
public string MSG { get; set; }
public MainViewModel()
{
MSG = "Test Message";
}
}
}
In 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
}
}
}
In App.xaml:
<Application.Resources>
<vm:ViewModelLocator xmlns:vm="using:MVVMLightUWPApp1.ViewModel"
x:Key="Locator" />
</Application.Resources>
In the View, set DataContext as below:
DataContext="{Binding Main, Source={StaticResource Locator}}"
Now, you can set binding to VM, for example:
<TextBlock Text="{Binding MSG}" FontSize="50" />
Enjoy it:)