WPF: Setting DataContext of a UserControl with Binding not working in XAML
Posted
by Grant Crofton
on Stack Overflow
See other posts from Stack Overflow
or by Grant Crofton
Published on 2010-04-18T11:09:22Z
Indexed on
2010/04/18
11:13 UTC
Read the original article
Hit count: 2893
wpf-binding
|mvvm
Hi, I'm trying to get my first WPF app working using MVVM, and I've hit a little binding problem.
The setup is that I have a view & viewModel which holds User details (the parent), and to try and keep things simple I've put a section of that view into a separate view & viewModel (the child). The child view is defined as a UserControl.
The issue I'm having is how to set the DataContext of the child view (the UserControl). My parent ViewModel has a property which exposes the child ViewModel, like so:
class ParentViewModel: INotifyPropertyChanged
{
public ChildViewModel childViewModel { get; set; }
//...
}
In the XAML for my parent view (which has it's DataContext set to the ParentViewModel), I try to set the DataContext of the child view as follows:
<views:ChildView
x:Name="ChildView"
DataContext="{Binding childViewModel}"/>
However, this doesn't work. The DataContext of the child view is set to the same DataContext as the parent view (i.e. the ParentViewModel), as if I wasn't setting it at all. I also tried setting the DataContext in the child view itself, which also doesn't work:
<UserControl x:Class="DietRecorder.Client.View.ChildView"
DataContext="childViewModel"
I have found a couple of ways around this. In the child view, I can bind everything by including the ChildViewModel in the path:
<SomeControl Visibility="{Binding Path=childViewModel.IsVisible}">
but I don't want the child view to have this level of awareness of the hierarchy. Setting the DataContext in code also works - however, I have to do this after showing the parent view, otherwise the DataContext just gets overwritten when I call Show():
parentView.Show();
parentView.ChildView.DataContext = parentViewModel.childViewModel;
This code also makes me feel uneasy, what with the LOD violation and all.
It's just the DataContext that seems to be the problem - I can bind other things in the child, for example I tried binding the FontSize to an int property just to test it:
<views:ChildView
x:Name="ChildView"
FontSize="{Binding Path=someVal}"/>
And that works fine.
But I'm sure binding the DataContext should work - I've seen similar examples of this kind of thing. Have I missed something obvious here? Is there a reason this won't work? Is there a spelling mistake somewhere? (I renamed things for your benefit so you won't be able to help me there anyway).
Any thoughts welcome.
Thanks, Grant
© Stack Overflow or respective owner