如何将图表系列绑定到数据更改的数据源?我当然需要图表系列来反映对基础数据的更改。我需要一个新的角度。
答案 0 :(得分:6)
我认为你的意思是来自WPF Toolkit的图表。使用ObservableCollection添加/删除事件和使用INotifyPropertyChanged进行更新事件。
的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));
}
}
}