【发布时间】:2014-04-17 17:37:28
【问题描述】:
我有MainWindow 类,我在其上显示DataChart 类中指定的实时图表。现在,当我运行我的应用程序时,图表将开始添加新数据并刷新,因为我在 DataChart 类的构造函数中为此启动了新线程。但我需要的是在单击MainWindow 类中定义的按钮后开始更新图表,而不是在应用程序启动后。但是当我从MainWindow 开始相同的 Thred 时,图表不会更新并且PropertyChangedEventHandler 为空。
在MainWindow:
private void connectBtn_Click(object sender, RoutedEventArgs e)
{
DataChart chart = new DataChart();
Thread thread = new Thread(chart.AddPoints);
thread.Start();
}
在DataChart:
public class DataChart : INotifyPropertyChanged
{
public DataChart()
{
DataPlot = new PlotModel();
DataPlot.Series.Add(new LineSeries
{
Title = "1",
Points = new List<IDataPoint>()
});
m_userInterfaceDispatcher = Dispatcher.CurrentDispatcher;
//WHEN I START THREAD HERE IT WORKS AND PROPERTYCHANGED IS NOT NULL
//var thread = new Thread(AddPoints);
//thread.Start();
}
public void AddPoints()
{
var addPoints = true;
while (addPoints)
{
try
{
m_userInterfaceDispatcher.Invoke(() =>
{
(DataPlot.Series[0] as LineSeries).Points.Add(new DataPoint(xvalue,yvalue));
if (PropertyChanged != null) //=NULL WHEN CALLING FROM MainWindow
{
DataPlot.InvalidatePlot(true);
}
});
}
catch (TaskCanceledException)
{
addPoints = false;
}
}
}
public PlotModel DataPlot
{
get;
set;
}
public event PropertyChangedEventHandler PropertyChanged;
private Dispatcher m_userInterfaceDispatcher;
}
我认为图表没有更新的问题是PropertyChanged=null,但我不知道如何解决它。如果有帮助,我会使用OxyPlot。
MainWindow.xaml:
<oxy:Plot Model="{Binding DataPlot}" Margin="10,10,10,10" Grid.Row="1" Grid.Column="1"/>
【问题讨论】:
-
没有代码/XAML 会导致任何绑定来填充您的 PropertyChanged 事件。什么或谁在“倾听”您的财产?
-
我没有看到您在哪里订阅了
PropertyChanged事件?我相信你的数据绑定了它,但那应该是不同的实例。 -
我已经添加了 MainWindow.xaml 代码。
-
什么是MainWindow的DataContext?
-
您在应用启动期间用于设置/初始化 DataChart 的代码看起来如何?正如你所说,既然它工作了,看到这段代码可能会提示什么是错误的以及为什么某些数据绑定不再工作......
标签: c# wpf multithreading inotifypropertychanged oxyplot