How to set DefaultValueAttribute of the PropertyGrid dynamically or at runtime?

不羁的心 提交于 2019-12-06 11:12:12

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!