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<ViewModel1>();
SimpleIoc.Default.Register<ViewModel2>();
SimpleIoc.Default.Register<ViewModel3>();
}
public ViewModel1 ViewModel1
{
get
{
return ServiceLocator.Current.GetInstance<ViewModel1>();
}
}
public ViewModel2 ViewModel2
{
get
{
return ServiceLocator.Current.GetInstance<ViewModel2>();
}
}
public ViewModel3 ViewModel3
{
get
{
return ServiceLocator.Current.GetInstance<ViewModel3>();
}
}
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)
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
and DataContext for views (either user controls or windows or whatever)
<UserControl
...
DataContext="{Binding ViewModel1, Source={StaticResource Locator}}"
... >
You could access the public properties of the ViewModel Locator programatically by getting the Locator from the Apps resources:
MyViewModel vm = (App.Current.Resources["Locator"] as ViewModelLocator).MyViewModel
or by creating another static instance in the ViewModelLocator class:
public class ViewModelLocator
{
public static ViewModelLocator Instance = new ViewModelLocator();
static ViewModelLocator(){ ... }
public MainViewModel Main
{
...
}
}
Similar Thread
If all you need is to bind a property from the main viewmodel, while inside the content control, just use this syntax:
... Binding="{DataContext.mainvmpropertyname, ElementName=xxxx}"
where xxxx is the Name attached to the content control (or any control that has the main viewmodel as its DataContext). Alternatively, you can use relative binding instead of element name.