Yochai Timmer
Yochai Timmer

Reputation: 49261

In Designer: Property default value is set, but property isn't called while setting default?

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

Answers (2)

Hans Passant
Hans Passant

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

Marc Gravell
Marc Gravell

Reputation: 1063569

Two options;

  • take away the default (bool defaults to false anyway)
  • use ShouldSerialize* to make it clear

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

Related Questions