WPF图表系列动态数据绑定 [英] WPF Chart Series Dynamic Databinding

查看:148
本文介绍了WPF图表系列动态数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将图表系列绑定到数据源更改数据源?我当然需要图表系列来反映底层数据的变化。我需要一个新鲜的角度。

How do I go about binding a chart series to a datasource where the data changes? I will of course need the chart series to reflect the changes to the underlying data. I need a fresh angle.

推荐答案

我认为你是WPF Toolkit的图表。使用ObservableCollection添加/删除事件和INotifyPropertyChanged进行更新事件。

I think you mean charts from WPF Toolkit. Use ObservableCollection for add/remove events and INotifyPropertyChanged for update events.

Xaml:

<chart:Chart>
    <chart:Chart.Series>
        <chart:LineSeries DependentValuePath="Value" IndependentValuePath="Time"
                Title="Example" x:Name="lineChart">
            <chart:LineSeries.DependentRangeAxis>
                <chart:LinearAxis Orientation="Y" Minimum="0" Maximum="20" />
            </chart:LineSeries.DependentRangeAxis>
        </chart:LineSeries>
    </chart:Chart.Series>
</chart:Chart>

代码背后:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var r = new Random();
        var Items = new ObservableCollection<ChartItem>(
            Enumerable.Range(0,5).Select(i=>new ChartItem(i,1)).ToList());
        var t = new System.Timers.Timer { Interval = 1000 };
        var start = DateTime.Now;
        //occurs every 1 second
        t.Elapsed += (s, e) => Dispatcher.Invoke((Action)(() =>
                            {
                                Items[r.Next(0, Items.Count)].Value = r.Next(20);
                                Items.Add(new ChartItem((e.SignalTime - start).TotalSeconds, r.Next(20)));
                            }));
        t.Start();
        lineChart.ItemsSource = Items;
    }
}

项目类:

public class ChartItem:INotifyPropertyChanged
{
    public ChartItem(double t, double v)
    {
        time = t;
        myVar = v;
    }

    private double time;

    public double Time
    {
        get { return time; }
        set
        {
            time = value;
            OnPropertyChanged("Time");
        }
    }

    private double myVar;

    public double Value
    {
        get { return myVar; }
        set
        {
            myVar = value;
            OnPropertyChanged("Value");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

另外,动态图表: http://dynamicdatadisplay.codeplex.com/

这篇关于WPF图表系列动态数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆