如何让PropertyGrid显示控件的Name属性

2025-05-19 04:56:21
推荐回答(1个)
回答1:

这是核心代码:

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 customFields = new List();

public override PropertyDescriptorCollection GetProperties()
{
return new PropertyDescriptorCollection(base.GetProperties()
.Cast().Union(customFields).ToArray());
}

public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
return new PropertyDescriptorCollection(base.GetProperties(attributes)
.Cast().Union(customFields).ToArray());
}
}

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;