繁体   English   中英

在点击事件中识别发件人按钮控件

[英]Recognizing sender button control in click event

我制作了一个自定义按钮,其中包含一个名为Data的字段。

我在运行时以编程方式将此按钮添加到我的 winform 中,并且在添加时我还为它们定义了一个点击事件。 好吧,其实我只有一种方法,我将新添加的按钮订阅到这个方法。

但是在点击事件中我想访问这个Data字段并将其显示为消息框,但似乎我的转换不正确:

    CustomButton_Click(object sender, EventArgs e)
    {
        Button button;
        if (sender is Button)
        {
            button = sender as Button;
        } 

        //How to access "Data" field in the sender button? 
        //button.Data  is not compiling!
    }

更新:

对不起,我提到“没有编译”。 .Data没有出现在智能感知中……

您需要强制转换为具有“数据”字段的自定义类的类型。

就像是:

YourCustomButton button = sender as YourCustomButton;

假设您的自定义按钮类型是CustomButton ,您应该这样做:

CustomButton_Click(object sender, EventArgs e){
  CustomButton button = sender as CustomButton;
  if (button != null){
      // Use your button here
  } 
}

如果您不想设置变量,那么简单的方法是:

((CustomButton)sender).Click

或者你想要什么。

我在 Github 上的 win forms 项目中发现了一个有趣的检查作业:

private void btn_Click(object sender, EventArgs e){

 // here it checks if sender is button and make the assignment, all in one shot.
 // Bad readability, thus not recommended
 if (!(sender is Button senderButton)) 
                return;

var _text = senderButton.Text;
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM