将自定义属性添加到标准控件
由于有点懒,我想将我的一些属性添加到控件中,而无需创建自定义控件的麻烦。
假设有一个 Button 控件,我想向它添加一个辅助 Tag 属性。
或者一个文本框,我想要一个 oldText 属性...
我不需要添加的属性显示在属性窗口中。我只需要在代码中使用它们。
有什么想法吗?
如果告诉我必须使用自定义控件或派生类,请不要回答。我需要工具栏上标准控件的易用性。
另一方面,像 Partial Class 这样的东西会做......
Being a bit lazy, I'd like to add some properties of mine to a control, WITHOUT the hassle of creating a custom control.
Say there is a Button control, I'd like to add a secondary Tag property to it.
Or a textbox I want an oldText property for it...
I do not need the added properties to show in the properties window. I just need to use them in code.
Any idea?
Please do NOT answer if telling me I HAVE to use custom control or derived class. I need the ease of use of standard controls from the toolbar.
On the other hand, something like Partial Class would do...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于 WPF
从 Button 扩展并添加所需的依赖属性。您不必从头开始创建自定义用户控件。
您还可以使用附加属性来添加其他功能,而不使用继承。
对于 winforms
我的 winforms 有点生疏,但我注意到你也可以简单地从 Button 扩展。
For WPF
Extend from Button and add the desired dependency properties. You don't have to create a custom user control from scratch.
You could also use attached properties to add additional functionality without using inheritance.
For winforms
My winforms is a little bit rusty, but I notice you can also simply extend from Button.
如果您不想扩展该类,而只想在代码中引用“属性”,则可以考虑构建一个
Dictionary
,其中T
是控件的类型,V
是您希望映射到控件的类型。如果想要将多个属性映射到同一控件,它可以是字符串或自定义类型。也许你有
你可以有
Dictionary;代码中的字典
,这将允许您将自定义属性和文本框映射在一起。If you do not want to extend the class and you just want to reference the "properties" in code, you could consider building a
Dictionary<T, V>
, whereT
is the type of control, andV
is the type you wish to map to the control. It could be a string or a custom type, in the case of wanting to have multiple properties mapped to the same control.Maybe you have
You could have
Dictionary<TextBox, CustomPropertyBag> dictionary
in your code, which would allow you to map your custom properties and textboxes together.我认为你最好的答案是我认为你不允许我们给出的答案 - 即使用继承来创建继承的控件。
但是,您也许可以使用 <代码>IExtenderProvider实现。
I think your best answer is the one that I think you're not allowing us to give - that is, use inheritance to create an inherited control.
However, you might be able to make a work-around using an
IExtenderProvider
implementation.