views:

807

answers:

2

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>
+1  A: 

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

AnthonyWJones
Until now I'd never heard of Silverlight Toolkit Chart controls. looks interesting but a BarChart should be simple enought to do with a userControl. I just wish There was a better way for a DataTemplate to have references to other object within the application. The DataTemplate seems so isolated it makes it hard to create truely dynamic content.
Matt.M
A: 

Have you tried the ActualHeight property? It should return you a value. RelativeSource with the TemplatedParent mode will work in a data template, but it will return the content presenter of the templated control/item, not the control/item itself (which it does when used in a control template). To experiment, put a button in the data template, and assign that binding expression (without the path) to its Tag property. Handle its Click event, and put a breakpoint in the event handler. Now when you run the project and click on the button, the breakpoint will be hit in your code, and you can see the object that it is binding to from the Tag property of the button (which you can see from the sender parameter). Hope this helps...

Chris Anderson