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

我的梦境 提交于 2019-12-04 04:01:01

问题


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 ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5367441/in-designer-property-default-value-is-set-but-property-isnt-called-while-sett

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!