knurd nerd
knurd nerd

Reputation: 324

WPF Binding up and down the Visual Tree

From a control in a WPF XAML view, I need to access the properties of another control that I can reach in the Visual Tree only when walking up to a common parent control and then down from there.

As an example:

<PageUserControl>
  <Grid>
    <TextBlock Text="Some example text" />
  </Grid>
  <TextBlock Text="{Binding Source={RelativeSource Mode=FindAncestor, AncestorType=PageUserControl, Path=??? I want to access the TextBlock}" />
</PageUserControl>

I want to access the text property of the first text block from the second text block (this is just an example).

What I would need is a way to combine relative sources, first one to go up the visual tree and find the PageUserControl, second one to go down the visual tree from there and find the grid and then finally a third one to find the text block within the grid.

Am I missing something here or is it just not possible?

I cannot add control IDs or something like this, it has to work with control types only.

I was thinking about something like a relative source that takes a XPath syntax, but it seems as if this was meant for another purpose (binding XML documents).

Maybe another idea?

Thank you!

Upvotes: 0

Views: 1077

Answers (1)

knurd nerd
knurd nerd

Reputation: 324

I found a solution for my problem. It is possible using this approach:

<PageUserControl>
  <Grid>
    <TextBlock Text="Some example text" />
  </Grid>
  <TextBlock Text="{Binding Path=Children[0].Children[0].Text,
    RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=PageUserControl}}" />
</PageUserControl>

While not very flexible, it is good enough for me.

Upvotes: 2

Related Questions