I have a Silverlight4 Chart with one Column Series. Instead of the legend displaying "Series 1", I would instead like the legend to contain one entry per column. Specifically, I'd like the legend to display the Dependent value of the column. The pie chart does exactly this, and is exactly what I want. I have tried manually setting the Items property of the Legend, but the property is read-only. I'm guessing writing my own LegendStyle is the best way to accomplish this, but I'm relatively new to XAML, so if there are any style experts who can do this easily I'd be forever grateful.
1
votes
2 Answers
2
votes
OK, here is how I solved this. First, here's my simple class:
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public Brush FavoriteColor { get; set; }
}
Next, the style that colors the columns came from David Anson's blog here: http://blogs.msdn.com/b/delay/archive/2009/02/04/columns-of-a-different-color-customizing-the-appearance-of-silverlight-charts-with-re-templating-and-mvvm.aspx
Using David's Pie Series legend code as an example, I eventually made this style for the Legend itself:
<Style x:Key="ColorByPreferenceLegend" TargetType="toolkit:Legend">
<Setter Property="Margin" Value="15,25" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="BorderBrush" Value="#FFDBDBDB" />
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0.442,0.005" StartPoint="0.558,0.995">
<GradientStop Color="#FFDBDBDB" />
<GradientStop Color="#FFFFFFFF" Offset="1" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Rectangle
Width="8" Height="8"
Fill="{Binding FavoriteColor}"
Stroke="{Binding FavoriteColor}"
StrokeThickness="1" Margin="3"/>
<TextBlock Margin="3" Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
And here's the chart markup:
<toolkit:Chart x:Name="chart" LegendStyle="{StaticResource ColorByPreferenceLegend}">
<toolkit:ColumnSeries IndependentValueBinding="{Binding Name}"
DependentValueBinding="{Binding Age}"
DataPointStyle="{StaticResource ColorByPreferenceColumn}" />
</toolkit:Chart>
Finally, here is how to get override the legend items, where _students is a List of Student objects:
ColumnSeries cs = chart.Series[0] as ColumnSeries;
cs.ItemsSource = _students;
cs.LegendItems.Clear();
foreach (Student s in _students)
cs.LegendItems.Add(s);