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!
    }

更新:

对不起,我提到.Data了智能感知中没有出现的“未编译”...

4

3 回答 3

8

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

就像是:

YourCustomButton button = sender as YourCustomButton;
于 2012-07-08T22:02:43.500 回答
3

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

CustomButton_Click(object sender, EventArgs e){
  CustomButton button = sender as CustomButton;
  if (button != null){
      // Use your button here
  } 
}
于 2012-07-08T22:03:56.390 回答
3

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

((CustomButton)sender).Click

或任何你想要的。

于 2019-04-26T21:04:53.263 回答