.NET add custom properties to winform controls -


it useful attach bunch of custom properties standard controls in .net, without creating set of custom controls.

i heard possible wpf, knows solution plain winform application?

why? example, when control has focus , textbox, or dropdownlist or combobox, want paint backcolor in custom property name: "focuscolor"

and of course, not want create custom buttons, combos or dropdown...

in wpf done attached properties. although there no exact equivalent in windows form, can implement iextenderprovider "attach" custom property control. property can used in designer, normal property. see code provided in this blog post example.

here's implementation "focuscolor" example:

[provideproperty("focuscolor", typeof(control))] public class focuscolorprovider : component, iextenderprovider {     private readonly dictionary<intptr, color> _focuscolors;     private readonly dictionary<intptr, color> _backcolors;      public focuscolorprovider()     {         _focuscolors = new dictionary<intptr, color>();         _backcolors = new dictionary<intptr, color>();     }      public bool canextend(object extendee)     {         return (extendee control);     }      public color getfocuscolor(control ctl)     {         color color;         if (_focuscolors.trygetvalue(ctl.handle, out color))         {             return color;         }         return ctl.backcolor;     }      public void setfocuscolor(control ctl, color color)     {         color backcolor;         if (!_backcolors.trygetvalue(ctl.handle, out backcolor))         {             backcolor = ctl.backcolor;         }          // same color backcolor, disable behavior         if (color == backcolor)         {             removefocuscolor(ctl);             ctl.lostfocus -= ctl_lostfocus;             ctl.gotfocus -= ctl_gotfocus;             _focuscolors.remove(ctl.handle);         }         else         {             _focuscolors[ctl.handle] = color;             if (ctl.focused)                 applyfocuscolor(ctl);             ctl.lostfocus += ctl_lostfocus;             ctl.gotfocus += ctl_gotfocus;         }     }      void ctl_gotfocus(object sender, eventargs e)     {         applyfocuscolor((control)sender);     }      void ctl_lostfocus(object sender, eventargs e)     {         removefocuscolor((control)sender);     }      void applyfocuscolor(control ctl)     {         _backcolors[ctl.handle] = ctl.backcolor;         ctl.backcolor = getfocuscolor(ctl);     }      void removefocuscolor(control ctl)     {         color color;         if (_backcolors.trygetvalue(ctl.handle, out color))         {             ctl.backcolor = color;             _backcolors.remove(ctl.handle);         }     } } 

add code project, compile, , add focuscolorprovider on form using designer. new focuscolor property should appear on property grid when select control, set color want. control's backcolor changed color when takes focus.


Comments