views:

40

answers:

1

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.

+1  A: 

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>

Code behind:

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;
    }
}

Item class:

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));
        }
    }

}

  

Also, dynamic charts: http://dynamicdatadisplay.codeplex.com/

vorrtex