此方法仅适用于telerik的控件,且是版本较早的。此处只用于做一个参考事例,直接复制不保证可运行。
1、前台
<telerikChart:RadChart x:Name="radChart"
Grid.Row="1"
d:LayoutOverrides="Width, Height">
<telerikChart:RadChart.DefaultView>
<telerikChart:ChartDefaultView>
<telerikChart:ChartDefaultView.ChartTitle>
<telerikChart:ChartTitle Content="标题"
HorizontalAlignment="Stretch" />
</telerikChart:ChartDefaultView.ChartTitle>
</telerikChart:ChartDefaultView>
</telerikChart:RadChart.DefaultView>
</telerikChart:RadChart>
2、后台
鼠标事件
private void Button_Click4(object sender, RoutedEventArgs e)
{
int maxItems = 30;
Random r = new Random();
List<Company> sampleData = new List<Company>();
for (int i = 0; i < maxItems; i++)
{
sampleData.Add(new Company(r.Next(200, 400)));
}
SeriesMapping seriesMapping = new SeriesMapping();
seriesMapping.LegendLabel = "My Custom Bars";
seriesMapping.SeriesDefinition = new BarSeriesDefinition();
seriesMapping.ItemMappings.Add(new ItemMapping("PurchasePrice", DataPointMember.YValue));
radChart.ItemsSource = sampleData;
radChart.SeriesMappings.Add(seriesMapping);
radChart.CreateItemStyleDelegate = BuildCustomItemStyle222;
}
图表颜色事件:
public Style BuildCustomItemStyle222(Control item, Style style, DataPoint point, DataSeries dataSeries)
{
if ((item as BaseChartItem) == null)
{
return style;
}
Style newStyle = new Style();
newStyle.BasedOn = style;
newStyle.TargetType = typeof(Shape);
Brush brush = (dataSeries[(item as BaseChartItem).CurrentIndex].DataItem as Company).GradeColor;
newStyle.Setters.Add(new Setter(Shape.FillProperty, brush));
return newStyle;
}
自定义数据结构:在这个地方将相关的颜色判定逻辑写上,赋值给一个字段。
public class Company
{
public double PurchasePrice
{
get; set;
}
public Brush GradeColor
{
get; set;
}
public Company(double price)
{
PurchasePrice = price;
if (price<250)
{
GradeColor = new SolidColorBrush(Colors.Black);
}
else if (price < 300)
{
GradeColor = new SolidColorBrush(Colors.Green);
}
else if (price < 350)
{
GradeColor = new SolidColorBrush(Colors.SkyBlue);
}
else if (price < 500)
{
GradeColor = new SolidColorBrush(Colors.GreenYellow);
}
}
}