簡體   English   中英

從用戶控件中刪除單個事件處理程序

[英]Remove single event handler from a user control

假設我有兩個用戶控件,並且想從該控件的一個實例中刪除事件處理程序。

為了說明這一點,我只是將其設置為用戶控件的按鈕:

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;
}
}

我已經在表單中添加了兩個超級按鈕,並且我想為SuperButton2禁用MouseEnter事件觸發。

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;

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

在您的情況下,您不需要一次刪除所有事件處理程序,只需刪除您感興趣的特定事件處理程序。使用-=刪除處理程序的方式與使用+=添加一個事件處理程序的方式相同:

button1.MouseEnter -= button1_MouseEnter;

為什么不只設置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);
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM