Search code examples
c#winformsuser-controls

C# WinForm Stop control property setting to default when it is set to be a value which is also the default


The problem is best explained through an example: I have a UserControl which has a default margin of 0, however I have an instance of the control which needs a margin of 3. I can set the margin of the control to be 2, 4, 10, or any other value other than 3 - but because 3 is the default value for margins in winforms - Visual Studio assumes I'm trying to reset the control to inherit the default value. This is obvious through the way the properties go bold:

When set to 5, the values are bold and the margin is set to 5: enter image description here

However, when I set it to 3, Visual Studio assumes I want to "reset" the value to its default (note the property text is no longer in bold):

enter image description here

Unfortunately, for this UserControl, the default value is actually 0 - so setting it to 3 actually sets the margin to 0 at run-time. I need to set the value to be 3 like I can with any other integer


Solution

  • You need to override DefaultMargin property of the user control:

    protected override Padding DefaultMargin
    {
        get { return new Padding(0); }
    }
    

    The default value for this property comes from CommonProperties.DefaultMargin which is internal and is Padding(3).