简体   繁体   中英

C# WinForms custom control default properties

How to you set the default properties for custom controls, ie when they are first dragged onto the form in the Designer?

Can't find an answer here or via Google; all I get is how to constrain the values.

Using Width & Height as examples, if I set them in the constructor they get applied to the control everytime the Designer is opened. How do I set them to a default which is never applied again after the user changes the properties?

Try using the DefaultValue attribute.

private int height;

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

What worked for me for properties that I can't override is using the new operator. For example, the MultiSelect property on a ListView control. I want MultiSelect to default to false , but I still want to be able to change it.

If I just set it to false in the constructor, or in 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 designer notices that true is the default, and so just doesn't set the property at all rather than explicitly setting it to what it thinks is already the default. But then the value ends up being false instead, because that is what is set in the constructor.

To get around this issue 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 functioning MultiSelect property that defaults to false rather than true , and the property can still be toggled on the new control.

EDIT: I encountered an issue having to do with using abstract forms. I've been using abstract form classes, with a concrete implementation that I switch to when I need to use the designer. I found that when I switched the class that I was inheriting from that the properties on my custom control would reset to the old defaults. I seem to have corrected this behaviour by setting properties to their defaults in the constructor of the custom control.

In the constructor, set the values of your properties you want to appear when you drag it onto the canvas. Or if they are the built in properties of the base control then set them in the designer code class.

The below will allow you to add the value when you display the form, after that you can set it as you want.

private int widthLength = 5;  

public int Width {      

     get { return widthLength ; } 
     set { widthLength = value;   
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM