Manikandan
Manikandan

Reputation: 261

How to bind a child user control's data context in the parent

<TextBlock Text="{Binding ChildGroupName, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, UpdateSourceTrigger=PropertyChanged,NotifyOnTargetUpdated=True,Mode=TwoWay}"
TargetUpdated="OnTextUpdated"/> 

Here ChildGroupName is a child control datacontext property. I want to bind ChildGroupName values to parent window.

Upvotes: 7

Views: 4950

Answers (2)

Mike Nakis
Mike Nakis

Reputation: 62130

Sheridan's answer did not work for me, because ReSharper was issuing a warning saying that "ChildPropertyName" is an unknown property.

Now, I did not actually try Sheridan's solution; it may be that it would have worked; it may be that WPF does smart tricks under the hood and manages to get things to work even with Sheridan's approach; however, for me, all warnings must always be enabled, and all code must be absolutely free from warnings, so I had to look for a solution that would not only work, but also work without eliciting a warning from ReSharper.

What worked for me was adding DataContext., as follows (without the extra clutter):

<TextBlock Text="{Binding DataContext.ChildPropertyName,
    ElementName=NameOfChildUserControl}" />

In other words, when you use ElementName, the DataContext becomes the element itself, (which makes sense,) so in order to get to the actual viewmodel you need to first reference the DataContext of the element.

Upvotes: 0

Sheridan
Sheridan

Reputation: 69987

You cannot use FindAncestor to data bind to a descendant's data... the clue is in its name. If the child UserControl is defined in the same XAML as the parent, then you can provide it with a name and then use the Binding.ElementName Property to data bind to its properties:

<TextBlock Text="{Binding ChildPropertyName, ElementName=NameOfChildUserControl, 
    UpdateSourceTrigger=PropertyChanged, NotifyOnTargetUpdated=True, Mode=TwoWay}" 
    TargetUpdated="OnTextUpdated" />

Upvotes: 2

Related Questions