Reputation: 49261
I have a piece of code that goes something like this:
[DefaultValue(false)]
public bool Property
{
set
{
blah = value;
someControl.Visible = value;
}
get
{
return blah;
}
}
When I look at the properties in the designer, the property is set to false (or true if I play with it).
But the property isn't actually set. The Visible value of the control isn't changed.
How can I make the designer actually set the property with the default value ?
Upvotes: 3
Views: 1786
Reputation: 942040
The [DefaultValue] attribute is only a hint to the designer and the serializer. It is completely up to you to ensure that the default value you promised in the attribute is in fact the value of the property. The property setter doesn't get called in your case because the serializer detected that the current value of the property equals the default value and can thus omit the property assignment. It is an optimization, it makes InitializeComponent() smaller and faster.
You ensure this simply by initializing the property value in your constructor. Beware that a control's Visible property defaults to true.
Upvotes: 3
Reputation: 1063569
Two options;
in the latter, you might want a bool? to track "explicit set" vs "implicit default":
private bool? property;
public bool Property
{
set
{
property = value;
someControl.Visible = value;
}
get
{
return property.GetValueOrDefault();
}
}
public void ResetProperty() { property = null; }
public bool ShouldSerializeProperty() { return property.HasValue; }
Note that Reset* and ShouldSerialize* are patterns recognized by the component-model.
Upvotes: 1