Designer resets property value
I have a problem setting a default value on a property, that is "updated" by Visual Studio Designer开发者_C百科 every time the form is modified in it.
Situation:
class MyHour {
MyHour() {}
MyHour(string h) {}
}
class MyPanel {
_FirstHour = new FirstHour("13:00");
[DefaultValue("13:00")]
Hour FirstHour {get { return _FirstHour; } set{...}}
}
When MyPanel is in the VS Designer, and the Designer is modified it (re)sets my(already pre-initialized):
MyHour myHour1 = new MyHour();
...
myPanel1.FirstHour = myHour1;
I want that it sets this(or just don't touch this property):
MyHour myHour1 = new MyHour("13:00");
...
myPanel1.FirstHour = myHour1;
If I understand the question correctly, you want to know why the VS designer does not initialize that property to what you have set with DefaultValue
?
The DefaultValueAttribute
does not actually cause that default value to be set, it merely informs the designer about a default value that the object is normally initialized with, so that the designer knows whether or not it has been modified (i.e. whether or not it needs to be serialized and should show as bold in the property grid).
To actually set a default value, you need to use an initializer on the field or set the value in the default (parameterless) constructor.
Even if not a "entirely satisfied" solution this is the one:
class MyPanel {
_FirstHour = new FirstHour("13:00");
[DefaultValue("13:00"),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
Hour FirstHour {get { return _FirstHour; } set{...}}
}
the Designer does not touch anymore FirstHour
property.
精彩评论