将自定义属性添加到标准控件

发布于 2024-10-17 15:32:42 字数 271 浏览 2 评论 0原文

由于有点懒,我想将我的一些属性添加到控件中,而无需创建自定义控件的麻烦。

假设有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

反目相谮 2024-10-24 15:32:42

对于 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.

悟红尘 2024-10-24 15:32:42

如果您不想扩展该类,而只想在代码中引用“属性”,则可以考虑构建一个 Dictionary,其中 T是控件的类型,V 是您希望映射到控件的类型。如果想要将多个属性映射到同一控件,它可以是字符串或自定义类型。

也许你有

class CustomPropertyBag
{
    public string OldText { get; set; }
    public string Tag { get; set; }
    // more
}

你可以有 Dictionary;代码中的字典,这将允许您将自定义属性和文本框映射在一起。

dictionary[textBox1].OldText = "whatever";

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>, where T is the type of control, and V 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

class CustomPropertyBag
{
    public string OldText { get; set; }
    public string Tag { get; set; }
    // more
}

You could have Dictionary<TextBox, CustomPropertyBag> dictionary in your code, which would allow you to map your custom properties and textboxes together.

dictionary[textBox1].OldText = "whatever";
血之狂魔 2024-10-24 15:32:42

我认为你最好的答案是我认为你不允许我们给出的答案 - 即使用继承来创建继承的控件。

但是,您也许可以使用 <代码>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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文