从另一个类调用线程时,PropertyChanged为null

本文关键字:PropertyChanged null 线程 另一个 调用 | 更新日期: 2023-09-27 17:58:59

我有一个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"/>

从另一个类调用线程时,PropertyChanged为null

您的问题是创建DataChart的新实例作为局部变量。您预计数据绑定会如何订阅其事件?

DataBinding将订阅设置为DataContext的实例的事件,因此您需要在同一实例上调用AddPoints。尝试以下操作:

private void connectBtn_Click(object sender, RoutedEventArgs e)
{
    DataChart chart = (DataChart)this.DataContext;
    Thread thread = new Thread(chart.AddPoints);
    thread.Start();
}