2012-08-14 144 views
0

說我有兩個用戶控件,我想從控件的一個實例中刪除一個事件處理程序。從用戶控件中刪除單個事件處理程序

爲了說明我剛纔提出一個按鈕爲用戶控件:

public partial class SuperButton : UserControl 
{ 
public SuperButton() 
{ 
    InitializeComponent(); 
} 

private void button1_MouseEnter(object sender, EventArgs e) 
{ 
    button1.BackColor = Color.CadetBlue; 
} 

private void button1_MouseLeave(object sender, EventArgs e) 
{ 
    button1.BackColor = Color.Gainsboro; 
} 
} 

我已經添加了兩個超級按鈕的形式,我想禁用MouseEnter事件燒成SuperButton2。

public partial class Form1 : Form 
{ 
public Form1() 
{ 
    InitializeComponent(); 
    superButton2.RemoveEvents<SuperButton>("EventMouseEnter"); 
} 
} 

public static class EventExtension 
{ 
public static void RemoveEvents<T>(this Control target, string Event) 
{ 
    FieldInfo f1 = typeof(Control).GetField(Event, BindingFlags.Static | BindingFlags.NonPublic); 
    object obj = f1.GetValue(target.CastTo<T>()); 
    PropertyInfo pi = target.CastTo<T>().GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance); 
    EventHandlerList list = (EventHandlerList)pi.GetValue(target.CastTo<T>(), null); 
    list.RemoveHandler(obj, list[obj]); 
} 

public static T CastTo<T>(this object objectToCast) 
{ 
    return (T)objectToCast; 
} 
} 

代碼運行,但它不工作 - 的MouseEnter和Leave事件仍然火災。我正在尋找這樣的事情:

superButton2.MouseEnter - = xyz.MouseEnter;

更新:閱讀本評論問題...

+0

'superButton2.MouseEnter - = button1_MouseEnter'不起作用? – 2012-08-14 04:03:16

+0

我需要在Form1中完成它,而不是在用戶控件中。除非嗯 – 2012-08-14 04:05:20

+0

@lc - 把這作爲一個答案,你可以。如:'public void DisableEvent(){button1.MouseEnter - = button1_MouseEnter;}' – 2012-08-14 04:06:50

回答

2

在你的情況,你不需要馬上刪除所有事件處理程序,只是具體的一個你有興趣使用-=在您使用+=同樣的方式來添加一個刪除處理程序:

button1.MouseEnter -= button1_MouseEnter; 
1

爲什麼不直接設置superButton2.MouseEnter = null;?這應該做的伎倆,直到某個地方MouseEnter被分配一個值。

只是一個更新,另一種方式來處理它,並且完全合法的:)

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Diagnostics; 

namespace TestControls 
{ 
    class SimpleButton:Button 
    { 
     public bool IgnoreMouseEnter { get; set; } 

     public SimpleButton() 
     { 
      this.IgnoreMouseEnter = false; 
     } 

     protected override void OnMouseEnter(EventArgs e) 
     { 
      Debug.Print("this.IgnoreMouseEnter = {0}", this.IgnoreMouseEnter); 

      if (this.IgnoreMouseEnter == false) 
      { 
       base.OnMouseEnter(e); 
      } 
     } 
    } 
} 
+0

無法編譯 - 'MouseEvent只能出現在+ =或 - =' – 2012-08-14 04:03:37

+1

的左側。這是非常錯誤的。 C#編譯器不會允許你這樣做,因爲有很多組播委託/事件發生,+ =和 - =是語法糖。 – 2012-08-14 04:09:53

+0

對於編輯,我很樂意讓你回到零+1。簡化問題有助於...禁用我看到解決方案的[禁用To Treeview控制動態展開/摺疊](http://superuser.com/questions/461374/record-directory-structure-change-migration) – 2012-08-14 13:31:10

相關問題