2011-03-21 17 views
0

使用它正在取得可重複使用一個單獨的類,需要通過它這會從上下文菜單中單擊事件中調用函數...傳遞一個方法的類事件處理器

問題:功能AREN輸入EventHandlers ....也是不同的EventHandler需要不同的參數在...例如的OnClose的退出按鈕....

編輯:

在類X

public void AddMenuItem(String name, EventHandler target) 
    { 
     MenuItem newItem = new MenuItem(); 
     newItem.Index = _menuItemIndex++; 
     newItem.Text = name; 
     newItem.Click += target; 

     _contextMenu.MenuItems.Add(newItem); 
    } 

在WPF:

addToTray.AddMenuItem("&Exit", Exit); 

我喜歡它,鏈接到的下面的方法,但在這一點上任何方法都可以。

private void ShouldIExit(object sender, System.ComponentModel.CancelEventArgs e) 
    { 
     // checks if the Job is running and if so prompts to continue 
     if (_screenCaptureSession.Running()) 
     { 
      MessageBoxResult result = System.Windows.MessageBox.Show("Capturing in Progress. Are You Sure You Want To Quit?", "Capturing", MessageBoxButton.YesNo); 
      if (result == MessageBoxResult.No) 
      { 
       e.Cancel = true; 
       return; 
      } 
     } 
     _screenCaptureSession.Stop(); 
     _screenCaptureSession.Dispose(); 
    } 
+0

這聽起來像你會創建一個調試噩夢 – Beth 2011-03-21 20:08:44

+0

@Beth - 我半睡半醒,這樣做是非常非常。 – 2011-03-21 20:22:31

回答

2

我猜的不可能再次刪除事件處理程序問題是您的ShouldIExit方法與EventHandler委託不匹配。嘗試改變它以採取常規EventArgs參數,並看看是否有效。最好避免爲不同的事件類型重用相同的事件處理程序。您應該將通用代碼封裝到單獨的方法中,然後讓不同的處理程序調用該代碼。

private bool CheckExit() 
{ 
    // checks if the Job is running and if so prompts to continue 
    if (_screenCaptureSession.Running()) 
    { 
     MessageBoxResult result = System.Windows.MessageBox.Show("Capturing in Progress. Are You Sure You Want To Quit?", "Capturing", MessageBoxButton.YesNo); 
     if (result == MessageBoxResult.No) 
     { 
      return false; 
     } 
    } 
    _screenCaptureSession.Stop(); 
    _screenCaptureSession.Dispose(); 
    return true; 
} 

private void ExitButtonClicked(object sender, System.ComponentModel.CancelEventArgs e) 
{ 
    if (!CheckExit()) 
    { 
     e.Cancel = true; 
    } 
} 

private void ExitMenuItemClicked(object sender, EventArgs e) 
{ 
    CheckExit(); 
} 
+0

哈哈,是死了沒有幫助編程:P ...謝謝你,還你在函數調用「!CheckExit();」之前加了一個感嘆號「 – 2011-03-22 14:25:21

+0

@ Reza M .:對不起,這是一個複製/粘貼錯誤。我修好了它。 – StriplingWarrior 2011-03-22 15:32:14

0

這是一個有點vauge,但你可能可以做

OnClose += (sender,e) => YourFunction(...) 

它有缺點,它如果需要的話

+1

雖然這可能不是問題,但值得注意的是,使用lambda表達式(或任何匿名方法)使得從事件處理程序中將其從消費代碼中移除非常棘手(如果不是不可能的話)。 – 2011-03-21 20:07:15

+0

好點,編輯 – svrist 2011-03-21 20:12:46

+0

對不起,昨晚因爲沒有睡覺而睡着了。我會更詳細地編輯我的問題。 – 2011-03-21 20:22:05

相關問題