经过多次咒骂和调查后,我找到了解决方案。这里有很多活动部分,所以我将尽可能简短地表达每个部分,同时仍然传达要点。
首先,我有一个想要跟踪的对象集合:
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; }
}
...
}
在我看来,我将定义饼图来显示篮子中水果的数量。这里最重要的因素是模板绑定切片模板
<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它与独立值绑定在一起,例如“香蕉”“葡萄”或其他值。这又被传递给值转换器。
<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