如何将图表系列绑定(bind)到数据发生变化的数据源?我当然需要图表系列来反射(reflect)基础数据的变化。我需要一个新的角度。
最佳答案
我认为您指的是 WPF 工具包中的图表。使用 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));
}
}
}
关于WPF 图表系列动态数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3631294/