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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With