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

前端 未结 2 523
予麋鹿
予麋鹿 2021-01-20 06:41

I have a piece of code that goes something like this:

[DefaultValue(false)]
public bool Property
{
    set
    {
        blah = value;
        someControl.Vi         


        
相关标签:
2条回答
  • 2021-01-20 07:30

    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.

    0 讨论(0)
  • 2021-01-20 07:36

    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.

    0 讨论(0)
提交回复
热议问题