4

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?

3 Answers 3

5

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> 
Sign up to request clarification or add additional context in comments.

2 Comments

This is great for if you are only going to use a child view model on just a part of your UserControl, but I think Alberto's answer covers the whole UserControl a little more cleanly. I'll have to keep this in mind for sections, though.
Although it was not as clean as Alberto's answer, the child viewmodel still lives in the context of the parent doing it this way, so this is the way I'm doing it.
2

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> 

Comments

1

Create the binding for the DataContext in this way, it will bind to a property on the mainViewModel:

DataContext="{Binding ChildVM, Source={StaticResource mainViewModel}}" 

1 Comment

This does not work like I thought it would. I used this and it made a different ChildVM not as a child to my original ParentViewModel. So, essentially, if I try to send a command back it doesn't know what properties are set in the ParentViewModel.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.