Wednesday, October 10, 2007

Where is UserControl.Text?

Creating UserControls is a very simple process from a high level. But as usual, the devil is in the details. Recently I was going through many of our controls here at work when I noticed that they were all using the “new” keyword to override the BackColor and Text properties. Somehow we’d managed to get by without this causing any problems until now. To correct this I had to override the OnBackColorChanged and OnTextChanged virtual methods.

After this was done I noticed that the Text property was no longer visible in intellisense for any of our UserControls. After looking closer at the object model I learned that UserControl inherits from Control which contains the Text property. So how come I couldn’t see the Text property? You can’t remove properties through inheritance.

It turns out there is a special designer attribute called System.ComponentModel.EditorBrowsableAttribute. This attribute can be placed on a property or method to determine change the visibility of that property or method in the designer. The possible visibility values (EditorBrowsableState) are Never, Advanced, and Always.

UserControl marks the Text property with EditorBrowsable( EditorBrowsableState.Never ).

I have no idea why Microsoft did this. I imagine there is some strange way of thinking which makes it make sense, but I haven’t figured it out yet.

To work around this, I had to override the Text property on a base class that all of our UserControls inherit from. Fortunately we already had a base class, otherwise I would have been forced to create one just so we could use the Text property correctly.

And for the record, yes, the Text property can be overridden. Why was it using the “new” keyword in the first place you ask? I don’t know. I think because whoever wrote the controls just didn’t know it was a virtual property.

2 comments:

  1. This did not work for me. Based on a suggestion at another site:

    [Browsable(true)]

    Worked for me. C# VS2008 .Net 3.5

    ReplyDelete
  2. It also appears that use need to have:

    DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)

    Otherwise, the designer doesn't generate code for setting the Text property.

    ReplyDelete

Note: Only a member of this blog may post a comment.