我正在定义一个与以下命令一起使用的自定义类属性网格 http://msdn.microsoft.com/en-us/library/aa302326.aspx控制。比如说,其中一个属性定义如下:
[CategoryAttribute("Section Name"),
DefaultValueAttribute("Default value"),
DescriptionAttribute("My property description")]
public string MyPropertyName
{
get { return _MyPropertyName; }
set { _MyPropertyName = value; }
}
private string _MyPropertyName;
如你所见DefaultValueAttribute
定义属性的默认值。这种默认值在两种情况下使用:
如果更改此属性值的默认值PropertyGrid
控件将以粗体显示它,并且
如果我打电话ResetSelectedProperty
的方法PropertyGrid
,
它将将该默认值应用于选定的单元格。
这个概念工作得很好,除了一个限制DefaultValueAttribute
。它只接受一个常量值。所以我很好奇,我可以动态设置它,例如从构造函数或稍后在代码中设置吗?
EDIT:我能够找到这段代码 http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx这让我可以阅读DefaultValueAttribute
:
AttributeCollection attributes = TypeDescriptor.GetProperties(this)["MyPropertyName"].Attributes;
DefaultValueAttribute myAttribute = (DefaultValueAttribute)attributes[typeof(DefaultValueAttribute)];
string strDefaultValue = (string)myAttribute.Value;
问题是,如何设置呢?
终于,我得到了答案!我遇到过很多展示如何实施的网站ICustomTypeDescriptor
and PropertyDescriptor
(这是一个 http://www.codeproject.com/Articles/4448/Customized-display-of-collection-data-in-a-Propert),如果您想将两页代码添加到 10 行类中,这很好。
这是一种更快的方法。我发现了一个提示。祝福那些真正发表建设性想法的人!
所以答案是在你的类中提供两种方法。一是private bool ShouldSerializePPP()
另一个是private void ResetPPP()
where 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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)