开发者

Add custom property to standard control

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 开发者_JAVA技巧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...


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.


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";


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜