如何防止在父类中调用PreviewKeyDown

时间:2014-02-04 15:52:21

标签: c#

我有两个控件。

class ControlA
{
    public ControlA()
    {
        //some code
        this.PreviewKeyDown += ControlA_PreviewKeyDown;
    }
    protected void ControlA_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        // do A things
    }
}

我还有一个继承控制A的控件B

class ControlB : ControlA
{
    public ControlB()
    {
        //some code
        this.PreviewKeyDown += ControlB_PreviewKeyDown;
    }
    protected void ControlB_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        // do B things
    }
}

触发PreviewKeyDown事件时,将触发ControlB_和ControlA_PreviewKeyDown。但我想只为ControlB触发ControlB_PreviewKeyDown。那可能吗?如果是这样,如何实现?

非常感谢你。

4 个答案:

答案 0 :(得分:2)

假设您可以更改ControlAControlB的代码,这是一个可能的解决方案:

class ControlA
{
    public ControlA(bool subscribe = true)
    {
        if (subscribe)
        {
            this.PreviewKeyDown += ControlA_PreviewKeyDown;
        }
    }
    protected void ControlA_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        // do A things
    }
}

class ControlB : ControlA
{
    public ControlB() : base(false)
    {
        //some code
        this.PreviewKeyDown += ControlB_PreviewKeyDown;
    }
    protected void ControlB_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        // do B things
    }
}

答案 1 :(得分:1)

尝试在ControlB处理程序中设置e.Handled = true;,并在ControlA处理程序中将逻辑包装在if(!e.Handled)

或者,因为您将ControlA处理程序保护为受保护,所以您可以在ControlB构造函数中取消订阅它:

    this.PreviewKeyDown += ControlB_PreviewKeyDown;

答案 2 :(得分:1)

你的“问题”是由于ControlB类构造函数也调用ControlA构造函数...你可以创建一个ControlA(bool fromParent = true),它不会添加this.PreviewKeyDown的处理程序+ = ControlA_PreviewKeyDown;

HTH

答案 3 :(得分:0)

PreviewKeyDown中,我们将检查发件人类型,以确定从哪个控制事件触发。 像

protected void ControlA_PreviewKeyDown(object sender, KeyEventArgs e)
{

    if (sender.GetType() == typeof(ControlA))
    {
        // do A things
    }

}



protected void ControlB_PreviewKeyDown(object sender, KeyEventArgs e)
{

    if (sender.GetType() == typeof(ControlB))
    {
        // do A things
    }

}