如何为WinRTXamlToolkit的LineChart系列自定义颜色?
为WinRTXamlToolkit的StateSeries自定义固定颜色
要解决每次重建图表时系列颜色自动变化的问题,你可以通过为每个StateSeries指定自定义DataPointStyle,固定折线和数据点的颜色,具体实现如下:
- 先准备一组固定的颜色集合(可根据需求调整):
private readonly List<Color> _fixedSeriesColors = new List<Color> { Colors.DarkCyan, Colors.Crimson, Colors.ForestGreen, Colors.Goldenrod, Colors.SlateBlue };
- 在循环创建
StateSeries时,按索引从颜色集合中取色,构建对应的数据点样式并绑定到系列:
LineChart.Series.Clear(); for (int index = 0; index < allDeviceTelemetry.Count; index++) { var deviceTelemetry = allDeviceTelemetry[index]; // 循环复用颜色集合,避免索引越界 var targetColor = _fixedSeriesColors[index % _fixedSeriesColors.Count]; // 创建自定义数据点样式 var dataPointStyle = new Style(typeof(StateDataPoint)) { Setters = { new Setter(StateDataPoint.StrokeProperty, new SolidColorBrush(targetColor)), new Setter(StateDataPoint.FillProperty, new SolidColorBrush(targetColor)), new Setter(StateDataPoint.StrokeThicknessProperty, 2), new Setter(StateDataPoint.WidthProperty, 5), new Setter(StateDataPoint.HeightProperty, 5) } }; ISeries series = new StateSeries() { Title = deviceTelemetry.DeviceId, IndependentValuePath = "Taken", DependentValuePath = "DeviceValueint", ItemsSource = deviceTelemetry.Measurements, DataPointStyle = dataPointStyle }; LineChart.Series.Add(series); }
额外优化
如果需要根据DeviceId绑定固定颜色(而非按索引),可以用字典存储设备ID与颜色的映射关系:
private readonly Dictionary<string, Color> _deviceColorMap = new Dictionary<string, Color> { { "Device_001", Colors.DarkCyan }, { "Device_002", Colors.Crimson }, // 其他设备颜色映射 };
循环时直接从字典中取值:
var targetColor = _deviceColorMap.TryGetValue(deviceTelemetry.DeviceId, out var color) ? color : Colors.Gray; // 未匹配到的设备用默认色
内容的提问来源于stack exchange,提问作者JohnKoz
相关产品推荐
相关产品推荐

