2011-11-14 51 views
-1

我正在使用WPF c#應用程序。我有一個包含數據網格的用戶控件。 我正嘗試從用戶控件發送一個公共事件,單擊鼠標右鍵。 這裏是創建公共事件空引用異常的事件

public event MouseButtonEventHandler datagridMouseClick; 

下它應該在DataGrid上的此事件處理函數被解僱:

private void dataGrid1_MouseDown(object sender, MouseButtonEventArgs e) 
{ 
    DependencyObject dep = (DependencyObject)e.OriginalSource; 
    while ((dep != null) && 
    !(dep is DataGridCell) && 
    !(dep is DataGridColumnHeader)) 
    { 
     dep = VisualTreeHelper.GetParent(dep); 
    } 
    if (dep is DataGridCell) 
    { 
     cell = dep as DataGridCell; 
     while ((dep != null) && !(dep is DataGridRow)) 
     { 
      dep = VisualTreeHelper.GetParent(dep); 
     } 
     row = dep as DataGridRow; 
    } 

    this.datagridMouseClick(sender, e); // GIVING ERROR 
} 

它給了我一個NullReferenceException。你能幫我弄清楚爲什麼。在此先感謝,任何幫助讚賞 問候

的事件在另一個類(實際上是另一個項目,因爲上面是開的DLL)處理.. 因此,它在其他類初始化這裏聽..

public Window1() 
    { 
     InitializeComponent();  
     search.datagridDoubleClick +=new RoutedEventHandler(search_datagridDoubleClick); 
     search.datagridMouseClick += new MouseButtonEventHandler(search_datagridMouseClick); /* Only this one gives error , even if the other one is handled exactly the same way in the code o.O */ 

    } 

在哪裏搜索是包含上述第一代碼

我覺得這裏的問題對象的名稱是,我試圖聽從另一個類/項目觸發的事件(因爲第一個代碼是從一個.dll)這樣,當前類不會初始化一個偵聽器保持它爲空。儘管我在上面的search.datagridDoubleClick上使用了這個精確的方法,並且完美地工作(這很奇怪)。 PS。我沒有得到-1,聽起來像是對我有價值的問題,反正...

+1

在哪條線上拋出異常? –

+1

哪一行給出錯誤? – ChrisF

+0

小心讓我們知道哪條線投擲? – asawyer

回答

4

你需要檢查是否有人通過檢查datagridMouseClick是否與Null不同來訂閱你的活動。

if (datagridMouseClick != null) 
    this.datagridMouseClick(sender, e); 
+0

我已經試過了。但這樣我所做的只是忽略代碼,因爲它是空的,並且事件沒有被觸發。我想知道爲什麼會出現異常 – user1035909

+0

那麼如果沒有人在聽這個事件,那麼有必要不要提起它。 你有沒有在你的代碼中的某個地方: datagridMouseClick + = SomeEventHandler? – MBen

+0

我同意......你必須將事件分配給某個東西(控件或對象) – Sandy