我希望有一个简单的 C# 问题!向按钮添加附加属性
你好 在 Windows 窗体(不是 WPF)上,我在 Flowlayout 上动态创建按钮,我想向它们添加一些属性,以便将其他值(int 和 string)与按钮一起存储以供以后使用。
Button bn = new Button();
bn.Text = "mybutton";
bn.Name = "mybutton";
toolTip1.SetToolTip(bn, "some tip");
bn.Location = new Point(200, 200);
bn.Size = new Size(110, 30);
bn.BackColor = SystemColors.Control;
bn.Show();
flowLayoutPanel1.Controls.Add(bn);
我想为每个按钮存储大约 6 个值,因为每个按钮的值都不同。
可以这样做吗?
hi
on a windows form (not WPF) I dynamically create buttons on a flowlayout and I would like to add some properties to them simply to store other values (int and string) with the buttons for latter use.
Button bn = new Button();
bn.Text = "mybutton";
bn.Name = "mybutton";
toolTip1.SetToolTip(bn, "some tip");
bn.Location = new Point(200, 200);
bn.Size = new Size(110, 30);
bn.BackColor = SystemColors.Control;
bn.Show();
flowLayoutPanel1.Controls.Add(bn);
I have about 6 values I would like to store with each button as it is different for each button..
Can this be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
对于非强类型信息,您可以使用 Tag 属性。否则,我认为你必须子类化。
For non-strongly-typed information, you can possibly use the Tag property. Otherwise, I think you'd have to subclass.
源自 Button: 就
我个人而言,我认为这是糟糕的代码。真的很糟糕的代码。
Derive from Button:
Personally, I think this is bad code. Really bad code.
是的。您可以将这样的数据分配给
Button.Tag
属性(继承自控制
)。该属性的类型为对象
,因此您可以为其分配任何您想要的内容。或者,您可以从
Button
继承。Yes. You can assign data like this to the
Button.Tag
property (inherited fromControl
). This property is typed as anobject
so you can assign anything you want to it.Alternative, you could inherit from
Button
.与所有 WinForms 控件一样,
Button
也有一个Tag
属性,可用于存储任意对象。Like all WinForms controls,
Button
also has aTag
property, which can be used to store arbitrary objects.您可以:
Tag 属性就是为此目的而设计的。
You can either:
The Tag property was designed for this very purpose.
在这种情况下,您想要做的事情是创建一个自定义控件。使用自定义控件,您比使用标准控件拥有更多的自由。您不仅可以继承您正在构建自定义控件的现有控件的所有功能。您还将有机会向自定义控件添加更多功能和属性。
来源: 微软 - Devloper Network。
https://msdn.microsoft.com/en -us/library/ff723977(v=表达式.40).aspx
Something you would like to do in this case would be to create a custom control. With a custom control, you have more freedom than with the standard control. Not only will you inherit all the functionality from the existing control you are building your custom control on. You will also have the opportunity to add more functionality and properties to your custom control.
Source: Microsoft - Devloper Network.
https://msdn.microsoft.com/en-us/library/ff723977(v=expression.40).aspx