Search code examples
c#.netwinformspropertiesgroupbox

How to add property to existing Winforms control


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?


Solution

  • I haven't tried this with GroupBox, but I'm thinking you could do something similar to the example with Button here.

    http://msdn.microsoft.com/en-us/library/7h62478z(v=vs.90).aspx

    Just create a new class, call it MyGroupBox or whatever you want:

    public class MyGroupBox : GroupBox {
        private string link;
    
        public string Link {get {return link;} set{link=value;} }
    }
    

    This inherits all the behavior/properties from GroupBox and adds a new property for a Link.

    Then you can just use it this way:

    MyGroupBox groupBox = new MyGroupBox();
    groupBox.Link = "www.google.com";
    

    I think this is cleaner than using the tag property, honestly. Mostly because it's not a tag, it's a link, and I like being able to name the property appropriately. :) Although tag might be easier if you are needing to do this for many controls and not just GroupBox.