如何绑定按钮和标签

How do I bind a button and a label

我将按钮控件扩展为也有 LabelName。当我按下按钮时,我需要在标签中写下按钮的名称。 我的第一个想法是使用事件——简单易行。 问题是:是否有更优雅的方式来做到这一点? (我被要求绑定按钮和标签)...

我认为最好的方法是使用动作侦听器,而使用动作侦听器的最佳方法是将其构建到扩展按钮控件的 class 中,以便用户不必自己执行此操作。它看起来像这样。

class Button2 : Button
{
    public string LabelName = "";
    public Button2()
    {
        this.Click += this.SetLabelName;
    }
    private void SetLabelName(object sender, EventArgs e)
    {
        this.LabelName = "Something?";
    }
//You could also do this instead.
    protected override void OnClick(EventArgs e)
        {
            base.OnClick(e);
        }
    }

如果您正在讨论更改 外部 标签控件的 Text 属性,那么只需在您的 属性 中创建一个 属性用于保存对标签的引用的按钮。您可以通过 IDE 像任何其他 属性:

一样进行设置

这是按钮 class:

public class MyButton : Button
{

    private Label _Label = null;

    public Label Label
    {
        get { return _Label; }
        set { _Label = value; }
    }

    protected override void OnClick(EventArgs e)
    {
        base.OnClick(e);
        if (this.Label != null)
        {
            this.Label.Text = this.Name;
        }
    }

}

这是我单击按钮后的标签: