Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bind directly to a child viewmodel?

Tags:

c#

mvvm

wpf

xaml

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?

like image 276
jporcenaluk Avatar asked Feb 14 '23 21:02

jporcenaluk


2 Answers

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>
like image 144
dkozl Avatar answered Feb 16 '23 10:02

dkozl


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>
like image 32
treehouse Avatar answered Feb 16 '23 10:02

treehouse