我正在编写一个程序,用户可以在表单中编辑控件属性。更改控件(文本框、标签等)属性我正在使用PropertyGrid。我希望添加自定义的可见属性,当控件在运行时变成False时不会隐藏它。仅在保存更改时更改可见性。
我使用Hide some properties in PropertyGrid at run-time的解决方案来显示控件的特定属性,如{Text、BackColor、ForeColor、Font、E 114大小E 215、E 116位置E 217、E 118可见E 219}等等。
private void CreateUIEditor(Control c)
{
if (c is Label)
{
propertyGrid.SelectedObject = new CustomObjectWrapper(c, new List<string>()
{ "Text", "BackColor", "ForeColor", "Font", "Visible"});
}
//...
}
public class CustomObjectWrapper : CustomTypeDescriptor
{
public object WrappedObject { get; private set; }
public List<string> BrowsableProperties { get; private set; }
public CustomObjectWrapper(object o, List<string> pList)
: base(TypeDescriptor.GetProvider(o).GetTypeDescriptor(o))
{
WrappedObject = o;
BrowsableProperties = pList;
}
public override PropertyDescriptorCollection GetProperties()
{
return this.GetProperties(new Attribute[] { });
}
public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
var properties = base.GetProperties(attributes).Cast<PropertyDescriptor>()
.Where(p => BrowsableProperties.Contains(p.Name))
.Select(p => TypeDescriptor.CreateProperty(
WrappedObject.GetType(),
p,
p.Attributes.Cast<Attribute>().ToArray()))
.ToArray();
return new PropertyDescriptorCollection(properties);
}
}发布于 2021-01-21 20:45:13
这里的基本思想是有一个影子属性,它不属于原始对象,而是显示在PropertyGrid中。这样的属性可以属于代理类本身。
下面的代理类将隐藏原始Visible属性,但是它显示了一个可以更改但不会更改原始对象的可见性的Visible属性:

下面是代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
public class CustomObjectWrapper : CustomTypeDescriptor
{
public object WrappedObject { get; private set; }
public List<string> BrowsableProperties { get; private set; }
public CustomObjectWrapper(object o, List<string> pList)
: base(TypeDescriptor.GetProvider(o).GetTypeDescriptor(o))
{
WrappedObject = o;
BrowsableProperties = pList;
}
public override PropertyDescriptorCollection GetProperties()
{
return this.GetProperties(new Attribute[] { });
}
public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
var properties = base.GetProperties(attributes).Cast<PropertyDescriptor>()
.Where(p => p.Name != "Visible")
.Where(p => BrowsableProperties.Contains(p.Name))
.Select(p => TypeDescriptor.CreateProperty(
WrappedObject.GetType(),
p,
p.Attributes.Cast<Attribute>().ToArray()))
.ToList();
if (BrowsableProperties.Contains("Visible"))
{
var p = TypeDescriptor.GetProperties(this, true)["Visible"];
properties.Add(TypeDescriptor.CreateProperty(
this.GetType(), p, new[] { BrowsableAttribute.Yes }));
}
return new PropertyDescriptorCollection(properties.ToArray());
}
public bool Visible { get; set; }
public override object GetPropertyOwner(PropertyDescriptor pd)
{
if (pd == null)
return base.GetPropertyOwner(pd);
else if (pd.Name == "Visible")
return this;
else
return WrappedObject;
}
}https://stackoverflow.com/questions/57070602
复制相似问题