You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OxyPlot.Wpf v2.1数据绑定不触发更新,实时图表失效该如何解决?

OxyPlot.Wpf v2.1数据绑定不更新实时图表问题及解决方案

问题背景

我此前使用OxyPlot.Wpf v2.0的C# WPF项目中,数据绑定功能运行完全正常。但升级到v2.1.2版本后,数据绑定不再处理更新,无法实现实时图表功能。

我编写了两个测试程序验证问题:两个版本均实现了INotifyPropertyChanged接口,数据属性定义如下:

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

...

private ObservableCollection<DataPoint> valueList1;
public ObservableCollection<DataPoint> ValueList1
{
    get => valueList1;
    set
    {
        valueList1 = value;
        OnPropertyChanged();
    }
}

private ObservableCollection<DataPoint> valueList2;
public ObservableCollection<DataPoint> ValueList2
{
    get => valueList2;
    set
    {
        valueList2 = value;
        OnPropertyChanged();
    }
}

构造函数中添加的测试数据在两个版本启动时均能正常显示,说明初始数据绑定逻辑无问题。但通过按钮向ObservableCollection属性添加新数据时,v2.0版本的图表会自动更新显示,v2.1版本则完全无反应,数据绑定未触发更新。

此外,升级到v2.1后,必须将原XAML中的图表定义移至后台代码实现:

v2.0的XAML写法

<oxy:Plot Title="OxyTest" >
    <oxy:Plot.Axes>
        <oxy:LinearAxis MaximumPadding="0.1" IsZoomEnabled="True" MajorStep="100" />
    </oxy:Plot.Axes>
    <oxy:Plot.Series>
        <oxy:AreaSeries Color="Red" Title="DataLine1" ItemsSource="{Binding Path=ValueList1}" />
        <oxy:LineSeries Color="Blue" Title="DataLine2" ItemsSource="{Binding Path=ValueList2}" />
    </oxy:Plot.Series>
</oxy:Plot>

v2.1的后台代码写法

MyModel = new PlotModel
{
    Title = "OxyTest",
};

MyModel.Axes.Add(new LinearAxis
{
    MaximumPadding = 0.1,
    IsZoomEnabled = true,
    MajorStep = 100
});

MyModel.Series.Add(new AreaSeries
{
    Color = OxyColor.FromRgb(255, 0, 0),
    Title = "DataLine1",
    ItemsSource = ValueList1
});

MyModel.Series.Add(new LineSeries
{
    Color = OxyColor.FromRgb(0, 0, 255),
    Title = "DataLine2",
    ItemsSource = ValueList2
});

解决方案1:手动触发图表刷新

v2.1版本必须手动调用InvalidatePlot()方法才能更新图表显示,而v2.0版本无需此操作。只需为集合的CollectionChanged事件绑定刷新逻辑即可:

ValueList1.CollectionChanged += (a, b) => MyModel.InvalidatePlot(true);
ValueList2.CollectionChanged += (a, b) => MyModel.InvalidatePlot(true);

解决方案2:使用OxyPlot.Contrib.Wpf包

向项目添加OxyPlot.Contrib.Wpf包,将XAML中的XMLNS从http://oxyplot.org/wpf修改为http://oxyplot.org/wpf/contrib,即可直接复用v2.0版本的XAML代码,无需处理CollectionChanged事件,数据绑定会自动生效。

注:官方OxyPlot文档目前处于建设中

内容的提问来源于stack exchange,提问作者roxxsteady

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 23:10:27