How to add property to existing Winforms control

gnarlybracket picture gnarlybracket · Jul 14, 2014 · Viewed 8.5k times · Source

I'm not sure if this is even possible. I've done some research, but haven't been able to find anything conclusive. There is a similar question here, but it's for WPF.

What I'd like to do is add a custom property to an existing WinForms GroupBox (or any control) on my form. For this example we'll use "Link". Say each GroupBox in my program contains a hyperlink, and then all I would need to do when I start my program is do this:

MyGroupBox.Link = "http:\\www.google.com\"

Later in my program I could set my hyperlink content to refer to MyGroupBox.Link.

Is it possible to manipulate a Winforms control like this? I'd rather not make a custom control if I don't have to.

I saw from this question that I could extend my control, but how I would that look in my particular case? Is that the same as creating a custom control?

Answer

terrybozzio picture terrybozzio · Jul 15, 2014

One way would be to use Extender Providers.They act like the ToolTip component when is added to a form, it provides a property called ToolTip to each control on that form.You could create this class:

    [ProvideProperty("Link", typeof(Control))]
    public class ExtendControls : Component, IExtenderProvider
    {
        private Dictionary<Control, string> links =
                                   new Dictionary<Control, string>();

        public bool CanExtend(object extendee)
        {
            return !(extendee is Form);
        }

        public void SetLink(Control extendee, string value)
        {
            if (value.Length == 0)
            {
                links.Remove(extendee);
            }
            else
            { 
                links[extendee] = value; 
            }
        }

        [DisplayName("Link")]
        [ExtenderProvidedProperty()]
        public string GetLink(Control extendee)
        {
            if (links.ContainsKey(extendee))
            {
                return links[extendee];
            }
            else
            {
                return string.Empty;
            }
        }
    }

What it does is it will provide the Link property to all controls exept the form.Now you create this class in your windowsforms project and build it,after you go to the designer of the form in the toolbox you should see the extendcontrols component drag it on to the Form and it will be placed in the component tray.Almost done...next you can use your new Link property either in the properties window on the desired control or in code like this(assuming you left the component to its default name):

//assuming ofcourse you have a button called button1
//i used button as the example you can use panel,datagridview,label,etc...
//to set it...
extendControls1.SetLink(button1, "sometest");
//to get it back...
string myLink = extendControls1.GetLink(button1);