The goal would be to directly access properties in the child ViewModel without losing the context of the entire ViewModel structure.
Currently, I have a resource in a dictionary that holds a reference to a ViewModel that I use as the data context for the whole application.
So, my datacontext for every view looks like this:
DataContext="{StaticResource mainViewModel}"
In my ViewModel I have nested child ViewModels like so:
public class ParentViewModel {
public ChildVM ChildVM { get; set; }
public ParentVM(){
ChildVM = new ChildViewModel();
}
}
public class ChildViewModel {
public string SomeProperty { get; set; }
}
In my view, I can access properties from the data context like so:
<Button Text="{Binding ChildVM.SomeProperty}"/>
But this gets very repetitive. I would like to be able to do:
<Button Text="{Binding SomeProperty}"/>
With my datacontext set to something like this pseudo:
DataContext="{StaticResource MainViewModel, Path=ParentVM.ChildVM}"
Any ideas?
You can change DataContext
for group of controls
<!-- DataContext is ParentViewModel -->
<Grid>
<!-- change DataContext to ChildViewModel -->
<Grid DataContext="{Binding Path=ChildVM}">
<Button Content="{Binding SomeProperty}"/>
<Button Content="{Binding AnotherChildProperty}"/>
</Grid>
</Grid>
You can set the DataContext on those controls' common parent like dkozl suggests. But if that sub visual tree is relatively large, you should probably consider making a UserControl dedicated to your childVM:
<Grid>
<ChildControl DataContext={Binding ChildVM}/>
</Grid>
<UserControl x:Class="ChildControl">
<Grid>
<Button Content="{Binding SomeProperty}"/>
<Button Content="{Binding AnotherChildProperty}"/>
</Grid>
</UserControl>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With