Finally, I got the answer! I've been running into a bunch of sites showing how to implement ICustomTypeDescriptor
and PropertyDescriptor
(here's one), which is fine if you want to add literally two pages of code to your 10-line class.
Here's a much faster way. I found a hint here. Bless those who actually post constructive ideas!
So the answer is to provide two methods in your class. One is private bool ShouldSerializePPP()
and another one is private void ResetPPP()
where PPP
is your property name. The former method will be called by the PropertyGrid
to determined if the property value was changed from a default one, and the latter method will be called whenever the PropertyGrid
item is reset to a default value.
Here's how my class should look with these additions, that will allow to set a default value for a property at a run-time:
[CategoryAttribute("Section Name"),
DescriptionAttribute("My property description")]
public string MyPropertyName
{
get { return _MyPropertyName; }
set { _MyPropertyName = value; }
}
private bool ShouldSerializeMyPropertyName()
{
//RETURN:
// = true if the property value should be displayed in bold, or "treated as different from a default one"
return !(_MyPropertyName == "Default value");
}
private void ResetMyPropertyName()
{
//This method is called after a call to 'PropertyGrid.ResetSelectedProperty()' method on this property
_MyPropertyName = "Default value";
}
private string _MyPropertyName;