经过多次发誓和调查,我找到了解决方案。这里有很多活动的部分,所以我会尽可能地简短,同时仍然传达要点。
对于初学者,我有一个我试图跟踪的对象集合:
public class PileOfFruit
{
public string Name {get; set; }
public int Count { get; set; }
}
在我的视图模型中,我有这些对象的集合。
public class BasketVM
{
...
private ObservableCollection<PileOfFruit> _FruitBasket = new ObservableCollection<PileOfFruit>();
public ObservableCollection<PileOfFruit> FruitBasket
{
get { return _FruitBasket; }
}
...
}
在我看来,我将定义显示篮子中水果数量的饼图。这里最重要的因素是模板绑定到 SliceTemplate
<chartingToolkit:Chart x:Name="ExampleChart">
<chartingToolkit:PieSeries ItemsSource={Binding FruitBasket
DependentValueBinding="{Binding Count}"
IndependentValueBinding="{Binding Name}">
<chartingToolkit:PieSeries.Palette>
<visualizationToolkit:ResourceDictionaryCollection>
<ResourceDictionary>
<Style x:Key="DataPointStyle" TargetType="Control">
<Setter Property="Template" Value="{StaticResource SliceTemplate}"/>
</Style>
现在在 app.xaml 或其他一些地方,我们可以放入 PieDataSeries 对象的模板。密切注意 Fill 上的值,它与独立值绑定,例如 'banana' 'grape' 或其他。这又被传递给一个值转换器。
<converters:FruitToColorConverter x:Key="FruitToColorConverter"/>
<ControlTemplate x:Key="SliceTemplate" TargetType="chart:PieDataPoint">
<Path Data="{TemplateBinding Geometry}"
Fill="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IndependentValue, Converter={StaticResource FruitToColorConverter}}"
Stroke="{TemplateBinding BorderBrush}">
....
关联的数据转换器最终将设置我们想要的颜色。所以如果我们做这样的事情......
public class FruitToColorConverter : IValueConverter
{
private SolidColorBrush Default = new SolidColorBrush(Colors.Black);
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null || (!(value is string))) { return Default; }
switch (value as string)
{
case "Apple":
return new SolidColorBrush(Colors.Red);
case "BlueBerry":
return new SolidColorBrush(Colors.Blue);
default:
return Default;
......
这就是您每次都能获得正确颜色的方式。如果我遗漏了任何内容或应该澄清,请告诉我,以便我进行更正。这里有很多活动部件.. =P