Search code examples
wpfsilverlightbindingrelativesource

Silverlight RelativeSource of TemplatedParent Binding within a DataTemplate, Is it possible?


I'm trying to make a bar graph usercontrol. I'm creating each bar using a DataTemplate.

The problem is in order to compute the height of each bar, I first need to know the height of its container (the TemplatedParent). Unfortunately what I have:

Height="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Height,  Converter={StaticResource HeightConverter}, Mode=OneWay}" 

does not work. Each time a value of NaN is returned to my Converter. Does RelativeSource={RelativeSource TemplatedParent} not work in this context? What else can I do to allow my DataTemplate to "talk" to the element it is being applied to?

Incase it helps here is the barebones DataTemplate:

<DataTemplate x:Key="BarGraphTemplate">
    <Grid Width="30">
        <Rectangle HorizontalAlignment="Center" Stroke="Black" Width="20" Height="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Height,  Converter={StaticResource HeightConverter}, Mode=OneWay}" VerticalAlignment="Bottom" />
    </Grid>
</DataTemplate>

Solution

  • To answer your question RelativeSource only works in a ControlTemplate it doesn't work in a DataTemplate.

    Is there a reason why the Silverlight Toolkit Chart controls don't work for you in creating a bar graph (or a Column Chart as the Tookit refers to vertical set of bars).