Silverlight图表图例:带柱系列的模拟饼图系列

时间:2011-11-19 21:25:10

标签: silverlight charts legend

我有一个带有一个列系列的Silverlight4图表。而不是显示“系列1”的图例,我希望每个列包含一个条目。具体来说,我希望图例显示列的Dependent值。饼图就是这样,正是我想要的。我试过手动设置Legend的Items属性,但属性是只读的。我猜写自己的LegendStyle是实现这一目标的最佳方式,但我对XAML相对较新,所以如果有任何风格专家能够轻松做到这一点,我将永远感激。

2 个答案:

答案 0 :(得分:2)

好的,这就是我解决这个问题的方法。首先,这是我的简单课程:

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Brush FavoriteColor { get; set; }
}

接下来,为这些列着色的样式来自David Anson的博客: 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

以David's Pie Series传奇代码为例,我最终为Legend本身制作了这种风格:

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

这是图表标记:

    <toolkit:Chart x:Name="chart" LegendStyle="{StaticResource ColorByPreferenceLegend}">
        <toolkit:ColumnSeries IndependentValueBinding="{Binding Name}"
                           DependentValueBinding="{Binding Age}"
                           DataPointStyle="{StaticResource ColorByPreferenceColumn}" />
    </toolkit:Chart>

最后,这里是如何覆盖图例项目,其中_students是一个学生对象列表:

    ColumnSeries cs = chart.Series[0] as ColumnSeries;
    cs.ItemsSource = _students;
    cs.LegendItems.Clear();
    foreach (Student s in _students)
        cs.LegendItems.Add(s);

答案 1 :(得分:1)

可能有效的一个技巧:通过LegendStyle使您当前的图例不可见,并自己手动构建图例。

您可以通过将可观察集合与列名绑定并将其绑定到与所需外观匹配的控件(即列表视图)来实现此目的。

相关问题