views:

91

answers:

2

I have a problem setting a default value on a property, that is "updated" by Visual Studio Designer 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;
+2  A: 

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.

Aaronaught
Yeah, I saw also from MSDN: "A member's default value is **typically** its initial value. A visual designer **can** use the default value to reset the member's value. Code generators **can** use the default values also to determine whether code should be generated for the member." Finally "A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You *must set the initial value in your code.* " I set, but the designer reset it back. What do you mean by "initializer"?
serhio
@serhio: A field initializer is declaring a field as `private string hour = "13:00"`. The last part is the initializer. If you can't do this (i.e. you're using auto-properties) then you have to initialize it in the constructor.
Aaronaught
@Aaronaught: I do already the initialization in MyObj. I'll update the code. I do the initialization, but designer "updates" my initialized hour with a new(empty) one.
serhio
@serhio: Your updated question has changed significantly. You can't simply set a string as the default value for a class. You need to implement a type converter and then initialize the default value with `[DefaultValue("13:00", typeof(Hour))]`. See here: http://msdn.microsoft.com/en-us/library/ayybcxe5.aspx
Aaronaught
A: 

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.

serhio