在单击事件中识别发送者按钮控件

6
我制作了一个自定义按钮,其中有一个名为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!
    }

更新:

很抱歉,我想说的是“无法编译”是指在 intelisense 中没有显示出 .Data...


你不必检查 sender 是否为 Button,因为 as 关键字会确保如果无法将变量转换为正确的类,则该变量为 null - Styxxy
4
这段代码不是有效的C#代码,所以当然不能正常工作。通常来说,一个自定义按钮控件应该重写OnClick方法,这样就可以实现自己的自定义点击事件行为。 - Hans Passant
你是如何尝试访问“Data”字段的? - Chibueze Opata
它只是在Intellisense中没有显示出来...现在我将其转换为CustomButton,它就显示了。 - Dumbo
4个回答

8

您需要将类型转换为具有Data字段的自定义类的类型。

就像这样:

YourCustomButton button = sender as YourCustomButton;

@Sean87 这个答案解决了无法访问 Data 字段的问题,但更好的长期方法是按照Hans的评论重写 OnClick 或可能引入自定义事件,以使事情更加类型安全-您目前依赖于将 customhandler (它只是标准处理程序签名) 连接到正确的按钮。使用自定义事件可以确保连接是正确的。 - David Hall

3

如果你不想简单地设置一个变量,可以这样操作:

((CustomButton)sender).Click

或者你想要的任何东西。


3
假设您的自定义按钮类型为CustomButton,您应该这样做:
CustomButton_Click(object sender, EventArgs e){
  CustomButton button = sender as CustomButton;
  if (button != null){
      // Use your button here
  } 
}

0
我在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;
...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接