Silverlight PieSeries自定义LegendItem与按钮(和FormattedRatio百分比)

时间:2012-09-28 14:23:48

标签: silverlight charts

对于我的PieSeries,我想要使用具有相关切片的填充颜色的按钮的图例,我还希望按钮具有使用FormattedRatio在工具提示中显示的百分比。这是我到目前为止所做的:

PieSeries image with buttons and orange slices

不幸的是,可以看出所有切片现在已经变成橙色,论坛已经说过这是一个标准问题,但没有明显的原因,LegendItem也没有“FormattedRatio”。 (我想说实例B:10.17%。)

有谁知道我如何能够获得颜色以及如何使用legendItem中的百分比?

修改

已经能够使用this answer更改切片的背景,但LegentItems不会根据新的颜色方案而改变。

enter image description here

颜色正确 - 我正在使用错误的测试数据。

1 个答案:

答案 0 :(得分:1)

有一种简单的方法可以更改颜色:重新定义Palette属性。 我已经回答了关于颜色的类似问题,这里是:https://stackoverflow.com/a/5626435/427225

对于图例项,无法访问FormattedRatio属性,因为工具包库包含大量错误,但您可以显示绑定项的属性,我将向您展示一个示例。 / p>

首先,您需要为LegendItem类创建样式。除了2个更改之外,它与默认值相同:您自己的ContentTemplate我将其命名为testItemTemplate,并将Content属性的绑定更改为{Binding DataContext}而不是前一个。

<UserControl.Resources>
    <Style x:Key="testLegendItemStyle" TargetType="chart:LegendItem">
        <Setter Property="ContentTemplate" Value="{StaticResource testItemTemplate}" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="chart:LegendItem">
                    <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
                        <StackPanel Orientation="Horizontal">
                            <Rectangle Width="8" Height="8" Fill="{Binding Background}" Stroke="{Binding BorderBrush}" StrokeThickness="1" Margin="0,0,3,0"/>
                            <datavis:Title Content="{Binding DataContext}" ContentTemplate="{TemplateBinding ContentTemplate}"/>
                        </StackPanel>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</UserControl.Resources>

<chart:Chart>
    <chart:PieSeries ItemsSource="{Binding Items}" IndependentValuePath="Title" DependentValuePath="Value" LegendItemStyle="{StaticResource testLegendItemStyle}" />
</chart:Chart>

接下来,您需要根据您的模型编写前面提到的testItemTemplate,这是示例。

C#视图模型

var items = new[] {
    new ItemViewModel(){ Title = "Apples", Value = 35, CalculatedAndFormattedValue = "1%" },
    new ItemViewModel(){ Title = "Bananas", Value = 43, CalculatedAndFormattedValue = "4%"  },
    new ItemViewModel(){ Title = "Oranges", Value = 29, CalculatedAndFormattedValue = "3%"  },
    new ItemViewModel(){ Title = "Cherries", Value = 51, CalculatedAndFormattedValue = "2%"  },
    new ItemViewModel(){ Title = "Lemons", Value = 31, CalculatedAndFormattedValue = "5%"  },
};

Xaml DataTemplate

<DataTemplate x:Key="testItemTemplate">
    <TextBlock>
        <Run Text="{Binding Title}" />
        <Run Text=" - " />
        <Run Text="{Binding CalculatedAndFormattedValue}" />
    </TextBlock>
</DataTemplate>

pie chart with custom legend items

毋庸置疑,您应该自己计算百分比