How can I bind directly to a child viewmodel?
c#, mvvm, wpf, xaml
Solution
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>
Problem
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?