Recoil
Recoil

Reputation: 65

Property Default Value does not work for a new control

I have a custom user control which expands and collapses. I have to have a second "open width" property that has to be set separately from the normal width property.

When I collapse the control, it makes the width 10. When I expand the control, it returns the control width back to the "open width" property, which has to be manually set to the normal width when the control is created.

The default new width on the control is 200, so for consistency I want to set the default "open width" property to 200 as well. So I have the following:

Private _mSideBarOpenWidth As Integer
<EditorBrowsable(EditorBrowsableState.Always)>
<Browsable(True)>
<DesignerSerializationVisibility( _
DesignerSerializationVisibility.Visible)>
<DefaultValue(200)>
<Category("SideBar")>
<Description("Sets the open Width of the SideBar control.")>
Public Property SideBarOpenWidth() As Integer
    Get
        Return _mSideBarOpenWidth
    End Get
    Set(value As Integer)
        _mSideBarOpenWidth = value
    End Set
End Property

When I drag a new control onto the form the default value is always 0. If I change it the value does persist, it just will not start at 200. I have done quite a bit of searching on this issue and I have tried the following:

cleaning/building/rebuilding the project
closing VisualStudio and opening it back up
deleting the form and creating a new one
using the control in a new project
setting <em>DesignerSerializationVisibility.Visible</em> to <em>.Content</em>
using <em>"200"</em> with the quotes as the default value

And various combinations of all those. None of that works and the default value on a new control dragged onto the form goes to zero. Needless to say I am at a loss on why the default value will not get set to 200 when it is created.

The only time I am even accessing the property is when I am setting the width of the control Me.Width = SideBarOpenWidth

Upvotes: 1

Views: 676

Answers (1)

it just will not start at 200

That is not what DefaultValue does. VS uses the DefaultValue to determine whether or not the current value differs from the default and so, should be serialized and show the property value in Bold in the Property IDE. It doesn't set the value. A remark from MSDN:

A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.

Attributes provide information about a class, property etc. Your property doesnt know about the DefaultValue attribute and they don't interact without code you add.

Instead, they specify information about the class or property (etc) to other things (designers, serializers etc). For instance, which Editor or TypeConverter to use. A good example is the Description or Category attributes - these provide information about your properties to VS which it uses in the Properties pane in the IDE.

Upvotes: 2

Related Questions