7
<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.

Keith Stein
  • 6,235
  • 4
  • 17
  • 36
Manikandan
  • 261
  • 3
  • 9

2 Answers2

2

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" />
Sheridan
  • 68,826
  • 24
  • 143
  • 183
0

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.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142