C# 从另一个类调用线程时,PropertyChanged为null
我有一个C# 从另一个类调用线程时,PropertyChanged为null,c#,wpf,multithreading,inotifypropertychanged,oxyplot,C#,Wpf,Multithreading,Inotifypropertychanged,Oxyplot,我有一个main窗口类,在这个类上我显示了在DataChart类中指定的实时图表。现在,当我运行我的应用程序时,图表将开始添加新数据并刷新,因为我在DataChart类的构造函数中为此启动了新线程。但我需要的是在单击main窗口中定义的按钮后开始更新图表,而不是在应用程序启动后。但当我从main窗口启动相同的Thred时,图表不会更新,PropertyChangedEventHandler为空 在主窗口中: private void connectBtn_Click(object sender,
main窗口
类,在这个类上我显示了在DataChart
类中指定的实时图表。现在,当我运行我的应用程序时,图表将开始添加新数据并刷新,因为我在DataChart
类的构造函数中为此启动了新线程。但我需要的是在单击main窗口中定义的按钮后开始更新图表,而不是在应用程序启动后。但当我从main窗口启动相同的Thred时,图表不会更新,PropertyChangedEventHandler
为空
在主窗口中
:
private void connectBtn_Click(object sender, RoutedEventArgs e)
{
DataChart chart = new DataChart();
Thread thread = new Thread(chart.AddPoints);
thread.Start();
}
在数据图表中
:
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;
}
您的问题是您正在将DataChart
的新实例创建为局部变量。您期望数据绑定如何订阅其事件
数据绑定将订阅实例的事件,该事件被设置为DataContext
,因此您需要在同一实例上调用AddPoints
。请尝试以下操作:
private void connectBtn_Click(object sender, RoutedEventArgs e)
{
DataChart chart = (DataChart)this.DataContext;
Thread thread = new Thread(chart.AddPoints);
thread.Start();
}
没有任何代码/XAML会导致任何绑定来填充PropertyChanged事件。什么或谁在“监听”你的财产?我看不出你在哪里订阅了PropertyChanged
事件?我相信您将数据绑定到它,但这应该是不同的实例。我添加了MainWindow.xaml代码。MainWindow的DataContext是什么?在应用程序启动期间用于设置/初始化DataChart的代码看起来如何?正如您所说,由于它在那时起作用,看到这段代码可能会给出一个提示,说明什么是错误的,以及为什么某些数据绑定不再起作用…'DataChart'类中的'PropertyChanged'在运行线程时仍然有空值(图表未更新),但我会尝试处理这个问题。
private void connectBtn_Click(object sender, RoutedEventArgs e)
{
DataChart chart = (DataChart)this.DataContext;
Thread thread = new Thread(chart.AddPoints);
thread.Start();
}