C # WinForms custom default control options

How do you set the default properties for user controls, i.e. when are they first dragged into the form in the constructor?

Unable to find an answer here or through Google; all i get is how to limit the values.

Using Width and Height as examples, if I set them in the constructor, they will be applied to the control every time the constructor is opened. How do I set them to a default value that never applies after a user changes properties?

+7
source share
4 answers

Try using the DefaultValue attribute.

private int height; [DefaultValue(50)] public int Height { get { return height; } set { height=value; } } 
+5
source

What worked for me for properties that I cannot override is using the new operator. For example, the MultiSelect property in a ListView control. I want MultiSelect to be false by default, but I still want to change it.

If I just set it to false in the constructor or in the InitializeComponent , the problem (I think) is that the default value is still true , so if I set the value to true in the designer, the developer notices that true is the default value. and therefore simply does not set the property at all, and does not explicitly set it to what, in his opinion, is already the default value. But then the value becomes false instead, because that is what is set in the constructor.

To get around this problem, I used the following code:

 /// <summary>Custom ListView.</summary> public sealed partial class DetailsListView : ListView { ... [DefaultValue(false)] public new bool MultiSelect { get { return base.MultiSelect; } set { base.MultiSelect = value; } } 

This allows the control to still have a valid MultiSelect property, which defaults to false rather than true , and the property can still be switched to the new control.

EDIT: I ran into a problem using abstract forms. I used abstract form classes, with a specific implementation that I switch with when I need to use the constructor. I found that when I switched the class that I inherited from the fact that the properties of my custom control would reset to the old default values. I seem to have fixed this behavior by setting the properties to their default values ​​in the constructor of the custom control.

+2
source

In the constructor, set the values ​​of your properties that you want to display when you drag them onto the canvas. Or, if they are built-in properties of the base control, set them in the constructor code class.

-one
source

Below you can add a value when the form is displayed, after which you can set it the way you want.

 private int widthLength = 5; public int Width { get { return widthLength ; } set { widthLength = value; } 
-one
source

All Articles