Reputation: 3453
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...
Upvotes: 2
Views: 4242
Reputation: 15579
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.
Upvotes: 1
Reputation: 126854
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";
Upvotes: 2
Reputation: 19100
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.
Upvotes: 3