2012-08-14 146 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

相关问题