2014-04-17 47 views
0

我有MainWindow類,其中im顯示​​類中指定的實時圖。現在,當我運行我的應用程序時,圖表將開始添加新數據並刷新,因爲我在​​類的構造函數中爲此啓動了新線程。但我需要的是在單擊MainWindow類中定義的按鈕之後開始更新圖表,而不是在應用程序啓動之後。但是當我從MainWindow開始相同時,圖表不更新並且PropertyChangedEventHandler爲空。當從另一個類調用線程時PropertyChanged爲null

MainWindow

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; 
    } 

我想,爲什麼圖表更新不及時的問題是PropertyChanged=null,但我無法弄清楚如何解決它。我使用OxyPlot如果有幫助。

MainWindow.xaml

<oxy:Plot Model="{Binding DataPlot}" Margin="10,10,10,10" Grid.Row="1" Grid.Column="1"/> 
+0

沒有任何代碼/ XAML會導致會填充PropertyChanged事件的任何綁定。什麼或誰在「傾聽」你的財產? –

+1

我沒有看到您訂閱「PropertyChanged」事件的位置?我相信你的數據綁定了它,但這應該是不同的實例。 –

+0

我已添加MainWindow.xaml代碼。 – BblackK

回答

0

您的問題是你創建的​​新的實例作爲局部變量。你期望數據綁定如何訂閱它的事件?

DataBinding將訂閱實例的事件,該事件被設置爲DataContext,因此您需要在同一個實例上調用AddPoints。請嘗試以下操作:

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

運行線程時,'DataChart'類中的'PropertyChanged'仍然爲空值(圖表未更新),但生病嘗試使用它。 – BblackK

相關問題