0

我有MainWindow一堂课,我在课堂上显示了课堂上指定的实时图表DataChart。现在,当我运行我的应用程序时,图表将开始添加新数据并刷新,因为我在类的构造函数中为此启动了新线程DataChart。但我需要的是在单击MainWindow类中定义的按钮后开始更新图表,而不是在应用程序启动后。但是当我从 开始相同的 Thred 时MainWindow,图表不会更新并且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"/>
4

1 回答 1

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();
}
于 2014-04-17T18:46:54.037 回答