如何在不指定页面变量的情况下覆盖自定义按钮的事件

I created a CustomButton, inherited from Button class. Then I created some event, like GotFocus, LostFocus, etc.

public sealed class CustomButton : Button
{
    public CustomButton()
    {
        this.DefaultStyleKey = typeof(CustomButton);
    }

    protected override void OnApplyTemplate()
    {
        this.GotFocus += CustomButton_GotFocus;
        this.LostFocus += CustomButton_LostFocus;

        base.OnApplyTemplate();

    }

    private void CustomButton_LostFocus(object sender, RoutedEventArgs e)
    {
        //some common behavior code
    }

    private void CustomButton_GotFocus(object sender, RoutedEventArgs e)
    {
        //some common behavior code
    }
}

Then I used this CustomButton in some pages. But in some specified pages, I don't want the CustomButton excute the GotFocus, LostFocus event.

那么如何在指定页面中覆盖这些事件呢?

I tried add GotFocus, LostFocus event in the specified pages, but it will finally run the common code behavior in CustomButton.

评论
  • 冷血动物
    冷血动物 回复

    您可以通过迭代页面控件来“退出” CustomButton中的事件:

    foreach(var cb in this.Controls.OfType<CustomButton>())
    {
        cb.GotFocus -= CustomButton_GotFocus;
        cb.LostFocus -= CustomButton_LostFocus;
    }
    

    我相信这应该可行。