But what if you want to also make the legend beside the chart clickable. That's not supported out of the box. You do this by changing the Legend Items template.
The template
Define a template like the following for the legend items. I've put this as a resource in the Grid that contains my Chart.<Grid.Resources> <Style x:Key="CategoryLegendItem" TargetType="toolkit:LegendItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="toolkit:LegendItem"> <StackPanel Orientation="Horizontal"> <Rectangle Width="8" Height="8" Fill="{Binding Background}" Stroke="{Binding BorderBrush}" StrokeThickness="1" Margin="0,0,3,0" /> <HyperlinkButton Content="{TemplateBinding Content}" Click="HyperlinkButton_Click" /> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> </Grid.Resources>Notice how I replaced the default Title element that displays the legend item text by a HyperlinkButton. That way it actually looks like something that can be clicked. This button also triggers the click event.
The code
First, the series LegendItemStyle must be set to the custom template. Since my chart is created in code I've put:series.LegendItemStyle = (Style)LayoutRoot.Resources["CategoryLegendItem"]Finally there's the HyperlinkButtons click handler.
private void HyperlinkButton_Click(object sender, RoutedEventArgs e) { RowPrestation row = (RowPrestation)((sender as HyperlinkButton) .DataContext as PieDataPoint).DataContext; PieSeries series = (PieSeries)(Chart.Child as Chart).Series[0]; series.SelectedItem = row; }Notice that the DataContext of the HyperlinkButton contains the PieDataPoint — in case of a pie chart — that goes with the legend item in question. And if you cast it, that points DataContext contains the bound object that was used as ItemsSource. Mine was a List<RowPrestation>.
Hi,
ReplyDeletevery interesting, thank you a lot!
I am facing the problem that I am using StackedAreaChart series instead of PieSeries. I can't figure out how to adapt the code in HyperlinkButton_Click().
It says Chart.Child ist not defined and RowPresentation is not found.
Would you be so kind and point me in the right direction for StackedAreaCharts?
Thx a lot!
"Chart" is actually the name of a panel
ReplyDeleteI put my pie chart in; so "Chart.Child"
just refers to the pie chart itself.
"RowPrestation" is a struct I defined.
You should use whatever struct or type
you used as ItemsSource of your chart.
I hope this can help you.