I have a main ViewModel
containing a List of items which I\'m using in a certain amount of UserControls
, which are displayed in a ContentCont
You can actually use the ViewModelLocator. Defaultly is uses the Inversion of Control Container, so even if you create a new instance of the Locator, you will get the same instance of singleton viewmodels from the container.
The Locator class:
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register();
SimpleIoc.Default.Register();
SimpleIoc.Default.Register();
}
public ViewModel1 ViewModel1
{
get
{
return ServiceLocator.Current.GetInstance();
}
}
public ViewModel2 ViewModel2
{
get
{
return ServiceLocator.Current.GetInstance();
}
}
public ViewModel3 ViewModel3
{
get
{
return ServiceLocator.Current.GetInstance();
}
}
then from code you can access it as
var vm1 = (new ViewModelLocator ()).ViewModel1;
you get the one and only instance of viewmodel.
from xaml: Resources (defaultly is in Application.Resources in App.xaml)
and DataContext for views (either user controls or windows or whatever)