3

我已经使用一些附加选项实现了自定义按钮控件。并将我的自定义按钮添加到表单中。当我设置 Form.Acception 是添加的自定义按钮时,我想在按钮中进行一些自定义。我想在自定义按钮类实现中自定义按钮外观,当它标记为 Form 的 AcceptButton 时。

任何人都建议我如何知道按钮被标记为按钮类中表单的 AcceptButton?

4

2 回答 2

0

错误的:

受保护的覆盖无效 OnLoad(EventArgs e) { base.OnLoad(e); if (((Form)this.TopLevelControl).AcceptButton == this) .... }

升级版:

public class MyButton : Button
    {
        public override void NotifyDefault(bool value)
        {
            if (this.IsDefault != value)
            {
                this.IsDefault = value;
            }

            if (IsDefault)
            {
                this.BackColor = Color.Red;
            }
            else
            {
                this.BackColor = Color.Green;
            }
        }
    }

在此处输入图像描述

于 2017-03-31T11:32:31.600 回答
-1

您可以通过其基类的 parent 属性遍历父母以找到表单Control

public partial class MyButton : Button
{
    public MyButton()
    {
        InitializeComponent();
    }

    private Form CheckParentForm(Control current)
    {
        // if the current is a form, return it.
        if (current is Form)
            return (Form)current;

        // if the parent of the current not is null, 
        if (current.Parent != null)
            // check his parent.
            return CheckParentForm(current.Parent);

        // there is no parent found and we didn't find a Form.
        return null;
    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();

        // find the parent form.
        var form = CheckParentForm(this);

        // if a form was found, 
        if (form != null)
            // check if this is set as accept button
            if (this == form.AcceptButton)
                // for example, change the background color (i used for testing)
                this.BackColor = Color.RosyBrown;
    }
}

由于递归,当按钮放置在面板上时它也可以工作。

注意:必须在调用 OnCreateControl 之前设置接受按钮 (例如在表单的构造函数中)


经过一番谷歌搜索后,我找到了一个标准实现:

您还可以使用:this.FindForm();

public partial class MyButton : Button
{
    public MyButton()
    {
        InitializeComponent();

    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();

        var form = FindForm();

        if (form != null)
            if (this == form.AcceptButton)
                this.BackColor = Color.RosyBrown;

    }
}

C# 6.0 中的事件更短:

public partial class MyButton : Button
{
    public MyButton()
    {
        InitializeComponent();

    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();

        if (this == FindForm()?.AcceptButton)
            this.BackColor = Color.RosyBrown;
    }
}

\o/

于 2017-03-31T11:55:36.720 回答