I don't know what is the correct way to create a viewmodel relationship if I use the approach that Views create instances of ViewModel and ViewModel has no reference to View.
Suppose we have ChildView control that creates an instance of its ViewModel that has SaveCommand.
<UserControl x:Class="App.ChildView" ...>
<UserControl.DataContext>
<local:ChildViewModel/>
</UserControl.DataContext>
<!-- some controls -->
</UserControl>
public class ChildViewModel
{
public RelayCommand SaveCommand { get; set; }
public ChildViewModel()
{
SaveCommand = new RelayCommand(SaveExecute);
}
private void SaveExecute()
{
Debug.WriteLine("Child data has been saved.");
}
}
Now, I put two controls in the parent view and want to execute SaveCommand on all children.
<Window x:Class="App.ParentView" ...>
<Window.DataContext>
<local:ParentViewModel/>
</Window.DataContext>
<Grid>
<local:ChildView x:Name="child1"/>
<local:ChildView x:Name="child2"/>
<Button Content="Save All" Command="{Binding ParentSaveCommand}">
<Grid/>
</Window>
public class ParentViewModel
{
public RelayCommand ParentSaveCommand { get; set; }
public ParentViewModel()
{
ParentSaveCommand = new RelayCommand(ParentSaveExecute);
}
private void ParentSaveExecute()
{
Debug.WriteLine("Saving all has started...");
// <childVM1>.SaveCommand.Execute();
// <childVM2>.SaveCommand.Execute();
// From where should I get ChildViewModel?
}
}
How correctly should I refer to child's ViewModel?
I found possible solutions:
- Add an interface to the ParentView that returns the child's ViewModel (like AngelSix did with the password)
- Create a class that will be able to bind the ChildView.DataContext to ParentView.DataContext.Child1ViewModel property.
.
Or maybe it's the wrong approach and ParentViewModel should create a ChildViewModel instances, and than ParentView should set DataContext for child1 and child2 (by binding of course)?
DataContext
from the parent instead of creating their own view models. - mm8