I have built a ViewModelLocator using Unity and have been successfully using it with singleton ViewModel instances. For example:
public class ViewModelLocator
{
private static readonly UnityContainer Container;
static ViewModelLocator()
{
Container = new UnityContainer();
if (ViewModelBase.IsInDesignModeStatic)
{
//Design Time Data Services
Container.RegisterType<IMyServiceServiceAgent, DesignMyServiceServiceAgent>();
}
else
{
//Real Data Services
Container.RegisterType<IMyServiceServiceAgent, MyServiceServiceAgent>();
}
Container.RegisterType<TreeViewViewModel>(new ContainerControlledLifetimeManager());
}
public TreeViewModel ViewModel
{
get
{
return Container.Resolve<TreeViewModel>();
}
}
}
The ViewModelLocator is defined as a resource in App.xaml:
<Application.Resources>
<ResourceDictionary>
<VMS:ViewModelLocator x:Key="ViewModelLocator" d:IsDataSource="True"/>
</ResourceDictionary>
</Application.Resources>
Which allows me to bind to the ViewModel in any of the Views as follows:
DataContext="{Binding TreeViewModel, Source={StaticResource ViewModelLocator}}" d:DataContext="{d:DesignInstance IsDesignTimeCreatable=False}"
My question is how do I maintain the same pattern (and the blendability) with multiple instances of the same ViewModel?
I have found reference to what I am looking to do in this post How to have multiple pairs "View-ViewModel"? but it does not go into the specifics of implementation.
What I want to be able to do is have multiple instances of these Views/ViewModel pairs for different data trees allowing copy and paste between them etc but cannot think how to cater for specific instances in the ViewModelLocator using the container?
I am assuming I need some kind of collection of ViewModels as per the post mentioned above, but how do I register that collection with the Unity Container and how do I bind to that in the View?
Any help is much appreciated.