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 ContentControl
on the main view. My current way of exchanging data between the ViewModels
exists of making a reference to each of the ViewModels
in the main ViewModel
, and one of the main ViewModel
in every UserControl
. However I do not know is this is the right way of doing this, since I have a ViewModelLocator
and I kind of expect this class to have some functionality to support something like this.
Can anyone please tell me if what I'm doing this OK, or if there is a better way of doing this in MVVM Light?
EDIT:
I found this when I was searching for something different, would this be a better solution?
private ViewModelLocator locator = new ViewModelLocator();
And then using the locator Properties to reference each ViewModel?
EDIT2:
Apparently what I thought would work doesn't, at first I had only references in the main ViewModel
and this worked, but when I try this in the UserControls
it kind of crashes my app. I'm currently trying the possible solution of first edit.
MainViewModel.cs (others are similar, with reference only to the main ViewModel)
public class MainViewModel : ViewModelBase
{
private ItemAddViewModel itemAddViewModel;
private ItemsViewModel itemsViewModel;
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
ItemsList = Item.GetItemsList();
itemAddViewModel = ServiceLocator.Current.GetInstance<ItemAddViewModel>();
itemsViewModel = ServiceLocator.Current.GetInstance<ItemsViewModel>();
ShowItemsView();
}
...
private void ShowItemsView()
{
CurrentControl = itemsViewModel;
}
...