How can I snap directly to the child model?

The goal is to directly access the properties in the child ViewModel without losing the context of the entire ViewModel structure.

I currently have a resource in a dictionary that contains a link to the ViewModel, which I use as the data context for the entire application.

So my datacontext for each view is as follows:

DataContext="{StaticResource mainViewModel}"

In my ViewModel model, I have nested child ViewModels, for example:

public class ParentViewModel {
    public ChildVM ChildVM { get; set; }
    public ParentVM(){
        ChildVM = new ChildViewModel();
    }
}

public class ChildViewModel {
    public string SomeProperty { get; set; }
}

In my opinion, I can access the properties from the data context as follows:

<Button Text="{Binding ChildVM.SomeProperty}"/>

But it becomes very repetitive. I would like to be able to:

<Button Text="{Binding SomeProperty}"/>

Something like this pseudo is installed in my datacontext:

DataContext="{StaticResource MainViewModel, Path=ParentVM.ChildVM}"

Any ideas?

+3
source share
3 answers

DataContext

<!-- DataContext is ParentViewModel -->
<Grid>
   <!-- change DataContext to ChildViewModel -->
   <Grid DataContext="{Binding Path=ChildVM}">
      <Button Content="{Binding SomeProperty}"/>
      <Button Content="{Binding AnotherChildProperty}"/>
   </Grid>
</Grid>
+4

DataContext , dkozl. , , , UserControl childVM:

<Grid>
    <ChildControl DataContext={Binding ChildVM}/>
</Grid>

<UserControl x:Class="ChildControl">
    <Grid>
      <Button Content="{Binding SomeProperty}"/>
      <Button Content="{Binding AnotherChildProperty}"/>
   </Grid>
</UserControl>
+2

Create a binding for the DataContext so that it will be bound to the mainViewModel property:

DataContext="{Binding ChildVM, Source={StaticResource mainViewModel}}"
+1
source

All Articles