I am simplifying a little here:
I have a tab control, and should like for individual tabs to have the power to create further tabs; siblings if you will. So I am calling the tab control the parent, and its tab pages the children.
Using MVVM, my tab control view model is something like this:
class ParentViewModel
{
ObservableCollection<ChildViewModel> _pages;
public ObservableCollection<ChildViewModel> Pages
{
get
{
if (_pages == null)
_pages = new ObservableCollection<ChildViewModel>();
return _pages;
}
}
public ParentViewModel()
{
Pages.Add(new ChildViewModel());
}
}
So I have a collection of ChildViewModel objects on my ParentViewModel.
This works a treat, and from inside the ParentViewModel I can of course easily add all the extra ChildViewModel objects I want to my collection and have it all nicely reflected in my Views.
What I want to do is allow a button press (for example) on a ChildView to result in the addition of another ChildViewModel to the collection on the ParentViewModel object.
I have read a lot about relay commands, routed commands, relativesource bindings, the dependancy injection pattern and so forth, but could someone tell me please the ‘proper’ (in an MVVM sense) way to achieve this, and exactly how it is best done. Thank you!
One of the ways I like to handle a situation like this is with Event Aggregating.
It is an ability added with Unity (if you aren’t already using it)
Basically you add the Event Aggregator to your Dependancy Injections and then your Parent would subscribe as a listener to the event and your children would publish the event.
The nice part about this is that the children have no concept of who is listening and the parent just knows it has an event request to handle. For more information you can go HERE!