4

这是 Oxyplot 官方页面显示的代码。命名空间 WpfApplication2

{
    using System.Collections.Generic;

    using OxyPlot;

    public class MainViewModel
    {
        public MainViewModel()
        {
            this.Title = "Example 2";
            this.Points = new List<DataPoint>
                              {
                                  new DataPoint(0, 4),
                                  new DataPoint(10, 13),
                                  new DataPoint(20, 15),
                                  new DataPoint(30, 16),
                                  new DataPoint(40, 12),
                                  new DataPoint(50, 12)
                              };
        }

        public string Title { get; private set; }

        public IList<DataPoint> Points { get; private set; }
    }
}

这是 XAML

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:oxy="http://oxyplot.codeplex.com"
        xmlns:local="clr-namespace:WpfApplication2"
        Title="Example 2 (WPF)" Height="350" Width="525">
    <Window.DataContext>
        <local:MainViewModel/>
    </Window.DataContext>
    <Grid>
        <oxy:Plot Title="{Binding Title}">
            <oxy:Plot.Series>
                <oxy:LineSeries ItemsSource="{Binding Points}"/>
            </oxy:Plot.Series>
        </oxy:Plot>
    </Grid>
</Window>

该示例运行良好,并在图表上显示 6 个点。我想要做的是绘制通过串行端口来的数据图。我想在 DispatcherTimer 的 Tick 事件中向图形添加新点。为了消除任何误解,我的问题范围是关于 oxyplot,(例如,答案中不应包含计时器事件的使用。)提前谢谢你。

4

1 回答 1

9

试试这个代码。

XAML:

<oxy:PlotView Model="{Binding DataPlot}"/>

主视图模型:

public PlotModel DataPlot { get; set; }
private double _xValue = 1;
public MainViewModel()
{
    DataPlot = new PlotModel();
    DataPlot.Series.Add(new LineSeries());
    var dispatcherTimer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 1) };
    dispatcherTimer.Tick += dispatcherTimer_Tick;
    dispatcherTimer.Start(); 
}

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    Dispatcher.CurrentDispatcher.Invoke(() =>
    {
       (DataPlot.Series[0] as LineSeries).Points.Add(new DataPoint(_xValue, Math.Sqrt(_xValue)));
        DataPlot.InvalidatePlot(true);
        _xValue ++;
    });
}

如果您不想在图表中从头到尾累积所有点,只需在添加每个新点后使用它:

if ((DataPlot.Series[0] as LineSeries).Points.Count > 10) //show only 10 last points
    (DataPlot.Series[0] as LineSeries).Points.RemoveAt(0); //remove first point

如果您想要更好的图表流程(此图表每秒更新一次),我建议使用Stopwatch,将添加点的代码放入自己的方法中,并在构造函数的线程中启动该方法。然后即Stopwatch.ElapsedMilliseconds用作x 值。

于 2014-04-20T00:35:33.757 回答