I'm trying to adjust my WP8 project from self made MVVM implementation to MVVM Light. I've successfully worked through this example and it worked perfectly. I've then started to repeat the same steps for my own project.
The application compiles without errors, but when I open my MainPage.xaml in Expression Blend, I will get this error:
Class project.Services.IDataService is already registered. App.xaml, Line 6, Column 5
If I look it up, it's the line where the ViewModelLocator is registered:
<Application.Resources>
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
</Application.Resources>
My ViewModelLocator.cs:
/// <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
// see: http://developingux.com/2012/06/10/how-to-fix-error-design-time-data-in-blend-with-mvvm-light/
if (!SimpleIoc.Default.IsRegistered<IDataService>())
{
SimpleIoc.Default.Register<IDataService, DesignDataService>();
}
}
else
{
// Create run time view services and models
if (!SimpleIoc.Default.IsRegistered<IDataService>())
{
SimpleIoc.Default.Register<IDataService, DataService>();
}
}
// only one ViewModel for the MainPage
SimpleIoc.Default.Register<MainViewModel>();
}
As you can see from my code comment, I've already tried the fix supposed here, but I'm still getting this error in Blend. There is no other place left where I could register the IDataService, so what could be the problem? Other questions here on SO are especially for desktop applications and does also only contain some kind of the above fix where there's first a check before the ViewModelLocator is registered.
Any ideas? :)
Update 1: I've managed to display my design time in Visual Studio. I was still manually referencing the DataContext in my Code Behind File. However, I still need to solve the problem that I cannot display the design time data in Blend. Judging from Visual Studios behavior it should work though?!
After reading the comments from the ViewModelLocator.cs again and again, I've seen that the DataContext for my MainPage.xaml was not set correctly:
DataContext="{Binding Source={StaticResource Locator}, Path=Main}"
instead of
DataContext="{Binding Main, Source={StaticResource Locator}}"
The Error in Blend stopped and I can see now in Blend and in VS the same design time data. But how did I oversee this error? Well, here's the explanation:
I've oriented myself on this tutorial, which was quite helpful. But my experience was, that it must be for some kind of older version of MVVM Light and something changed in the version I'm using now. Jesse used the Binding without the Path. However, this is working in his example. But here in my special case I needed to supply the Path so that the Locator could identify the correct property for my MainViewModel (which is here Main).