繁体   English   中英

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

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

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

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

private string _MyPropertyName;

如您所见, 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;

问题是,你如何设置它?

最后,我得到了答案! 我已经遇到了很多站点,展示了如何实现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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM