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

时间:2014-04-17 17:37:29

标签: c# wpf multithreading inotifypropertychanged oxyplot

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

1 个答案:

答案 0 :(得分:0)

您的问题是您正在创建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();
}