views:

21

answers:

2

My question is with respect to properly binding the property of one element to another.

Here is the structure of my code:

(1) Data Template contains a grid (let's called the grid GridA), and in the grid, I specify an instance of a control, called ControlA.

(2) ControlA is a UserControl that contains a Grid. There is custom logic in ControlA (code-behind) that dynamically builds the content - but in a nutshell, it uses another data template.

(3) The data template for ControlA consists of another Grid. I want to bind the Height property for this grid in this data template to the Height property of the Grid in the data template referenced in my first bullet point above (the grid called GridA).

Here is the XAML that I have used for the binding, but, essentially, it isnt working, as its not finding the Grid:

<Grid Height="{Binding Path=ActualHeight, RelativeSource={RelativeSource FindAncestor,AncestorType=Grid,AncestorLevel=2},UpdateSourceTrigger=PropertyChanged}">

</Grid>

I understand that by specifying AncestorLevel=2, that it will use the second "found" occurrence of the type that you are looking for, in this case, the type is Grid. So in my mind, it will first find the Grid in ControlA, then it will continue to walk up the tree and find the Grid in the first data template, which is the Grid named GridA. This should be the second occurrence, correct?

Please help.

Thank you.

Chris

A: 

Since you're beginning your search from the second grid, you actually want ancestor level = 1 (which is the default). Observe:

<Grid x:Name="first">
    <Grid x:Name="second">
        <Grid x:Name="third" Tag="{Binding Name, RelativeSource={RelativeSource FindAncestor, AncestorType=Grid, AncestorLevel=2}}">
            <!-- displays "first", not "second" -->
            <TextBlock Text="{Binding Tag, ElementName=third}"/>
        </Grid>
    </Grid>
</Grid>

BTW, your design sounds like it fights WPF's layout system rather than embracing it. As such, you're probably creating a lot of unnecessary pain for yourself.

HTH,
Kent

Kent Boogaart
Thanks for the feedback. I agree with you on comments regarding the design - that was not my choice and was done prior to my addition to this project.Regarding your suggestion, it is the third grid that must bind to the first grid. So, your example for the third grid specifies AncestorLevel=2, which is what I stated in my example. So, I am confused. If we are both specifying AncestorLevel=2, what am I doing incorrectly?
Chris
I have three grids, whereas you state you have two. But maybe I misunderstood your question. Does it work if you change your ancestor level to 1?
Kent Boogaart
A: 

Am I missing something, or could you just use the SharedSizeGroup property of the RowDefinitions and set Grid.IsSharedSizeGroup="True" on the outermost control?

Goblin