C# 遍历控件属性,针对性隐藏。
发布网友
发布时间:2022-05-12 17:01
我来回答
共1个回答
热心网友
时间:2023-10-14 21:26
解决方案:为了实现只显示所需属性,我创建了一个派生自CustomTypeDescriptor的类CustomObjectWrapper,这个类的BrowsableProperties属性为你需要显示的控件属性,在构造函数中进行了设置,我这里设置的是Text和BackColor,然后在窗体的后台代码的Form_Load事件中实例化一个CustomObjectWrapper类,将你需要的设置的控件在其构造函数中传入,并赋给PropertyGrid的SelectedObject 属性。CustomObjectWrapper类:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
public class CustomObjectWrapper : CustomTypeDescriptor
{
public object WrappedObject { get; private set; }
public List<string> BrowsableProperties { get; private set; }
public CustomObjectWrapper(object wrappedObject)
: base(TypeDescriptor.GetProvider(wrappedObject).GetTypeDescriptor(wrappedObject))
{
WrappedObject = wrappedObject;
BrowsableProperties = new List<string>() { "Text", "BackColor" };
}
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);
}
}
}
Form的Load事件:
private void Form1_Load(object sender, EventArgs e)
{
this.propertyGrid1.SelectedObject = new CustomObjectWrapper(this.textBox1);
}
运行界面效果如下:
追问谢谢您。