如何动态或在运行时设置PropertyGrid的DefaultValueAttribute?

c00*_*0fd 2 .net c# reflection propertygrid winforms

我正在定义一个与PropertyGrid控件一起使用的自定义类.比如,其中一个属性定义如下:

[CategoryAttribute("Section Name"),
DefaultValueAttribute("Default value"),
DescriptionAttribute("My property description")]
public string MyPropertyName
{
    get { return _MyPropertyName; }
    set { _MyPropertyName = value; }
}

private string _MyPropertyName;
Run Code Online (Sandbox Code Playgroud)

如您所见,DefaultValueAttribute定义了属性的默认值.这种默认值用于两种情况:

  1. 如果此属性值从默认值更改,则 PropertyGrid控件将以粗体显示,并且

  2. 如果我调用ResetSelectedProperty方法PropertyGrid,它会将该默认值应用于所选单元格.

这个概念很好,除了一个限制DefaultValueAttribute.它只接受一个常量值.所以我很好奇,我可以动态地设置它,例如,从构造函数或稍后的代码中设置它吗?

编辑:我能够找到这个代码让我读到DefaultValueAttribute:

AttributeCollection attributes = TypeDescriptor.GetProperties(this)["MyPropertyName"].Attributes;
DefaultValueAttribute myAttribute = (DefaultValueAttribute)attributes[typeof(DefaultValueAttribute)];
string strDefaultValue = (string)myAttribute.Value;
Run Code Online (Sandbox Code Playgroud)

问题是,你如何设置它?

c00*_*0fd 12

最后,我得到了答案!我已经遇到了很多网站,展示了如何实现ICustomTypeDescriptorPropertyDescriptor(这里是一个),如果你想在你的10行类中添加两页代码,这很好.

这是一种更快捷的方式.我在这里找到了一个提示.祝福那些真正发表建设性意见的人!

所以答案是在你的班级中提供两种方法.一个是private bool ShouldSerializePPP(),另外一个private void ResetPPP()地方PPP是你的属性名称.前一个方法将被调用PropertyGrid以确定属性值是否从默认值更改,并且只要PropertyGrid项目重置为默认值,就会调用后一个方法.

以下是我的类应该如何看待这些添加,这将允许在运行时为属性设置默认值:

[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;
Run Code Online (Sandbox Code Playgroud)