How to get a parent value in multibinding

Darf Zon picture Darf Zon · Mar 15, 2012 · Viewed 13.3k times · Source

I'm using dataTemplate. This is the template:

   <ItemsControl ItemsSource="{Binding RAM.Partitions}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <TextBlock Text="{Binding Position, StringFormat={}{0}k}"/>
                    <Grid Grid.Column="1">
                        <Border>
                            <Border.Height>
                                <MultiBinding Converter="{StaticResource MultiplyConverter}">
                                    <Binding ElementName="LayoutRoot" Path="ActualHeight"/>
                                    <Binding Path="Size" />
                                    <Binding Path="RAM.Size" />
                                </MultiBinding>
                            </Border.Height>
                        </Border>
                    </Grid>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

Can you see this line?

<Binding Path="RAM.Size" />

That line throws me an exception, it should be because RAM.Size is from a parent element. How might I get that value?

Thanks in advance!

Answer

Matt Hamilton picture Matt Hamilton · Mar 15, 2012

So you're trying to get to the RAM.Size value on the same object that your ItemsControl is getting its ItemsSource from?

See if this works:

<MultiBinding Converter="{StaticResource MultiplyConverter}"> 
    <Binding ElementName="LayoutRoot" Path="ActualHeight"/> 
    <Binding Path="Size" /> 
    <Binding Path="DataContext.RAM.Size"
        RelativeSource="{RelativeSource Mode=FindAncestor,AncestorType=ItemsControl}" /> 
</MultiBinding>

So the binding is going up in through the visual tree to the ItemsControl, then binding to the Ram.Size property of its DataContext.