常用的跟描述相关的信息:
descriptionattribute - 设置显示在属性下方说明帮助窗格中的属性文本。这是一种为活动属性(即具有焦点的属性)提供帮助文本的有效方法。可以将此特性应用于 maxrepeatrate 属性。
categoryattribute - 设置属性在网格中所属的类别。当您需要将属性按类别名称分组时,此特性非常有用。如果没有为属性指定类别,该属性将被分配给杂项类别。可以将此特性应用于所有属性。
browsableattribute – 表示是否在网格中显示属性。此特性可用于在网格中隐藏属性。默认情况下,公共属性始终显示在网格中。可以将此特性应用于 settingschanged 属性。
readonlyattribute – 表示属性是否为只读。此特性可用于禁止在网格中编辑属性。默认情况下,带有 get 和 set 访问函数的公共属性在网格中是可以编辑的。可以将此特性应用于 appversion 属性。
defaultvalueattribute – 表示属性的默认值。如果希望为属性提供默认值,然后确定该属性值是否与默认值相同,则可使用此特性。可以将此特性应用于所有属性。
defaultpropertyattribute – 表示类的默认属性。在网格中选择某个类时,将首先突出显示该类的默认属性。可以将此特性应用于 appsettings 类。
添加自定义属性的步骤,首先创建一个类并继承ExpandableObjectConverter,然后在类里面实现需要的转换方法。如果直接在自定义对象前加上[System.ComponentModel.TypeConverter(typeof(ExpandableObjectConverter))]这样的格式转换,也可以在属性表内显示。
关键代码如下:
[System.ComponentModel.TypeConverter(typeof(XYZTConverter))]
public struct XYZT
{
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
public float T { get; set; }
public XYZT(float x, float y, float z, float t)
{
this.X = x;
this.Y = y;
this.Z = z;
this.T = t;
}
}
public class XYZTConverter : System.ComponentModel.ExpandableObjectConverter
{
public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
try
{
string[] tokens = ((string)value).Split(';');
return new XYZT(float.Parse(tokens[0]), float.Parse(tokens[1]), float.Parse(tokens[2]), float.Parse(tokens[3]));
}
catch
{
return context.PropertyDescriptor.GetValue(context.Instance);
}
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
{
return true;
}
if (destinationType == typeof(InstanceDescriptor))
{
return true;
}
//调用基类方法处理其他情况
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
XYZT p = (XYZT)value;
return p.X + ";" + p.Y + ";" + p.Z + ";" + p.T;
}
public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
return true;
//return base.GetPropertiesSupported(context);
}
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
return TypeDescriptor.GetProperties(value, attributes);
//return base.GetProperties(context, value, attributes);
}
}
实现代码:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
mytest mytest = new mytest();
private void button1_Click(object sender, EventArgs e)
{
propertyGrid1.SelectedObject = mytest;
}
}
public class mytest
{
public XYZT XYZT{get;set;}
}
显示效果如下: