首页 > 解决方案 > OxyPlot 触发 LineSeries 颜色变化通知

问题描述

我有一个 oxyplot 和一个带有 ColorPickers 的列表框来选择 LineSeries 颜色。

我想,问题是,添加到 PlotModel.Series 的 LineSeries 在我向它们添加 DataPoints 之前没有有效的颜色集。

所以问题是:在手动更改 ColorPickers 之前,如何让 ColorPickers 在启动后占用 LineSeries 的有效颜色?

我想避免在实例化时手动设置颜色,现在我对 PlotModel 分配给它们的颜色感到满意。

OxyPlot 和列表框:

<oxy:PlotView Grid.Column="0" Grid.Row="0" x:Name="plot1" Model="{Binding PlotModel}"/>
...
<ListBox Grid.Column="1" Grid.Row="0" ItemsSource="{Binding PlotModel.Series}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <CheckBox IsChecked="{Binding Path=IsVisible}" />
                <xctk:ColorPicker Width="30" ShowDropDownButton="False" SelectedColor="{Binding Path=Color, Mode=TwoWay,  UpdateSourceTrigger=PropertyChanged, Converter={StaticResource ColorConverter}}" Opacity="1" ShowRecentColors="True"/>
                <TextBlock Text="{Binding Path=Title}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

ColorConverter XAML 资源:

<local:ColorConverter x:Key="ColorConverter"></local:ColorConverter>

和 C# 代码:

[ValueConversion(typeof(OxyColor), typeof(Rect))]
class ColorConverter : IValueConverter
{      
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is OxyColor)
        {
            var color = (OxyColor)value;
            if ((targetType == typeof(Color)) || (targetType == typeof(Color?)))
            {
                return color.ToColor();
            }

            if (targetType == typeof(Brush))
            {
                return color.ToBrush();
            }
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (targetType == typeof(OxyColor))
        {
            if (value is Color)
            {
                var color = (Color)value;
                return OxyColor.FromArgb(color.A, color.R, color.G, color.B);
            }

            if (value is SolidColorBrush)
            {
                var brush = (SolidColorBrush)value;
                Color color = brush.Color;
                return OxyColor.FromArgb(color.A, color.R, color.G, color.B);
            }
        }

        return null;
    }

}

这就是我动态添加新 LineSeries 的方式:

LineSeries l = new LineSeries { LineStyle = LineStyle.Solid, Title = title };
PlotModel.Series.Add(l);

标签: c#wpfdata-bindingivalueconverteroxyplot

解决方案


修改 LineSeries 实例化工作:

LineSeries l = new LineSeries { LineStyle = LineStyle.Solid, Title = title, Color = PlotModel.DefaultColors[PlotModel.Series.Count] };

还有其他方法吗?例如某种颜色属性更改事件?


推荐阅读