这是核心代码:
class ControlDescriptionProvider : TypeDescriptionProvider
{
private static TypeDescriptionProvider defaultTypeProvider =
TypeDescriptor.GetProvider(typeof(Control));
public ControlDescriptionProvider() : base(defaultTypeProvider) { }
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
{
ICustomTypeDescriptor defaultDescriptor = base.GetTypeDescriptor(objectType, instance);
return new TitleCustomTypeDescriptor(defaultDescriptor);
}
}
class TitleCustomTypeDescriptor : CustomTypeDescriptor
{
public TitleCustomTypeDescriptor(ICustomTypeDescriptor parent)
: base(parent)
{
customFields.Add(new NamePropertyDescriptor());
}
private List
public override PropertyDescriptorCollection GetProperties()
{
return new PropertyDescriptorCollection(base.GetProperties()
.Cast
}
public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
return new PropertyDescriptorCollection(base.GetProperties(attributes)
.Cast
}
}
class NamePropertyDescriptor : PropertyDescriptor
{
public NamePropertyDescriptor() : base("(Name)", null) { }
public override bool CanResetValue(object component)
{
return false;
}
public override Type ComponentType
{
get
{
return typeof(Control);
}
}
public override object GetValue(object component)
{
Control control = (Control)component;
return control.Name;
}
public override bool IsReadOnly
{
get
{
return false;
}
}
public override Type PropertyType
{
get
{
return typeof(string);
}
}
public override void ResetValue(object component)
{
throw new NotImplementedException();
}
public override void SetValue(object component, object value)
{
Control control = (Control)component;
control.Name = value.ToString();
}
public override bool ShouldSerializeValue(object component)
{
return false;
}
}
下面是测试代码:
ControlDescriptionProvider provider = new ControlDescriptionProvider();
TypeDescriptor.AddProvider(provider, typeof(Control));
//下面测试下Label,任何控件都可以。
Label label = new Label();
label.Name = "123";
propertyGrid1.SelectedObject = label;