User Control custom properties lose state when use

2019-07-04 06:39发布

I have a user control with custom properties as follows:

[DefaultValue(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Description("Gets or sets whether the \"Remove\" button is visible.")]
public bool ShowRemoveButton
{
    get
    {
        return this.removeButton.Visible;
    }
    set
    {
        this.removeButton.Visible = value;
    }
}

The control contains a standard button control. This property is used to show or hide the button. The user control is built in a separate project assembly. I placed it on a form and I can set and unset the above property and everything appears to be working just fine. However, when the project containing the user control is rebuilt, the property value flips to "false", which is not the default.

How can I prevent the custom property from losing/altering its state when the control is rebuilt?

2条回答
smile是对你的礼貌
2楼-- · 2019-07-04 07:39

An easy way to keep any contained controls' properties from being reset upon (de)serialization of related properties is to use a private backing field for the property and assign a default value that matches the DefaultValue attribute's parameter. In this case, that's the _showRemoveButton = true declaration/assignment below.

[DefaultValue(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Description("Gets or sets whether the \"Remove\" button is visible.")]
public bool ShowRemoveButton
{
    get
    {
        return _showRemoveButton;
    }
    set
    {
        _showRemoveButton = value;
        this.removeButton.Visible = value;
    }
}
private bool _showRemoveButton = true;
查看更多
不美不萌又怎样
3楼-- · 2019-07-04 07:40

The problem is that the DefaultValueAttribute only tells the designer what the default value is for the property. It controls whether the property is displayed in bold, and what the value gets reset to when you right-click on the property and choose "Reset" from the context menu.

What it doesn't do is set the property to a particular value at run-time. To do that, you'll need to place code in your user control's constructor method. For example:

// set default visibility
this.removeButton.Visible = true;

Otherwise, as you've described, the value of the property will be reset when you rebuild the project. It will show up in bold in the Properties window of the designer, because it doesn't match the default (as specified in the DefaultValueAttribute), but that attribute doesn't change what the value is set to.

查看更多
登录 后发表回答