日期:2014-05-17  浏览次数:20840 次

请问如何判断一个TextBox已经存在TextChanged事件处理函数?
添加TextChanged事件处理函数:this.textBox1.TextChanged += this.textBox1_TextChanged;
删除TextChanged处理函数:this.textBox1.TextChanged -= this.textBox1_TextChanged;

但有没简单的办法判断textBox1已经存在TextChanged 处理函数?以及如何判断已经存在指定的textBox1_TextChanged?


------解决方案--------------------
从事件设计的角度,你不应该关心TextChanged事件有多少个订阅(或者说你不拥有那些订阅)。
你只应该关心由你自己添加的处理函数。
------解决方案--------------------
添加事件处理函数的时候先-=,再+=,就不会重复添加
------解决方案--------------------

public bool HasTextChangedEvent(Control ctl, string eventName)
{
    PropertyInfo propertyInfo = ctl.GetType().GetProperty("Events", BindingFlags.NonPublic 
------解决方案--------------------
 BindingFlags.Instance);
    EventHandlerList events = propertyInfo.GetValue(ctl, null) as EventHandlerList;
    FieldInfo fieldInfo = (typeof(Control)).GetField("EventText", BindingFlags.NonPublic 
------解决方案--------------------
 BindingFlags.Static);
    Delegate del = events[fieldInfo.GetValue(null)];
    if (del == null) return false;
    foreach (Delegate d in del.GetInvocationList())
    {
         if (d.Method.Name == eventName)
             return true;
     }
     return false;
}


MessageBox.Show(HasTextChangedEvent(textBox1, "textBox1_TextChanged").ToString());

------解决方案--------------------
引用:

public bool HasTextChangedEvent(Control ctl, string eventName)