How to set initial value for user control property?

I am creating a user control and I wonder how you set the initial value for a property at design time? I have an Alignment property that has 4 values ​​enum TopRight, TopLeft, BottomRight and BottomLeft. Therefore, when the user removes the user control on the form, I want the initial value of the property to always be BottomRight. How can i do this?

+7
initialization c # properties user-controls
source share
3 answers

You must set the initial value in the constructor of your user control or declare a support variable for this property.

The DefaultValue attribute does not set the initial value. As stated in the documentation , you need to set the initial value in the code; the designer will use the DefaultValue attribute to determine whether to generate code to set the property.

+7
source share

Set Attributes for a Property

 [DefaultValue(typeof(AlignmentType), "BottomRight")] public AlignmentType Alignment { } 

Edit: in fact, this only helps the developer determine if the property should otherwise be specified in the initialization code.

With this in mind, you simply use your constructor to set a default value or set a default value with a variable declaration.

+3
source share

In your user control code, after initializing the property with a value of BottomRight.

0
source share

All Articles