I got this code in a user control:
[DefaultValue(typeof(Color), "Red")]
public Color MyColor { get; set; }
How can I change MyColor
to be its default value?
-
The
DefaultValueAttribute
does not set the property to the value, it is purely informational. The Visual Studio designer will display this value as non-bold and other values as bold (changed), but you'll still have to set the property to the value in the constructor.The designer will generate code for the property if the value was set by the user, but you can remove that code by right clicking on the property and clicking
Reset
. -
Are you initializing
MyColor
in your constructor?The
DefaultValue
attribute does not actually set any values. It simply instructs the designer for which value to not generate code and will also show the default value non-bold to reflect this. -
The "DefaultValue" attribute does not write code for you... but rather it is used for you to tell people (such as Mr Property Grid, or Mr Serializer Guy) that you plan to set the default value to Red.
This is useful for things like the PropertyGrid... as it will BOLD any color other than Red... also for serialization, people may choose to omit sending that value, because you informed them that it's the default :)
-
DefaultValueAttribute
is not used by the compiler, and (perhaps confusingly) it doesn't set the initial value. You need to do this your self in the constructor. Places that do useDefaultValueAttribute
include:PropertyDescriptor
- providesShouldSerializeValue
(used byPropertyGrid
etc)XmlSerializer
/DataContractSerializer
/ etc (serialization frameworks) - for deciding whether it needs to be included
Instead, add a constructor:
public MyType() { MyColor = Color.Red; }
(if it is a
struct
with a custom constructor, you need to call:base()
first) -
It is informal, but you can use it via reflection, for example, place in your constructor the following:
foreach (FieldInfo f in this.GetType().GetFields()) { foreach (Attribute attr in f.GetCustomAttributes(true)) { if (attr is DefaultValueAttribute) { DefaultValueAttribute dv = (DefaultValueAttribute)attr; f.SetValue(this, dv.Value); } } }
Marc Gravell : In the example given, the attribute is set against the property, not the field.Melursus : I adapt your code for property and it's work well, thx!Yossarian : Ok, so - rewrite - foreach (FieldInfo f in this.GetType().GetFields()) as foreach (PropertyInfo f in this.GetType().GetProperties())Samuel : Wait wtf? Why is this accepted? If this answers your question, you need to rewrite your question.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.