我有一个实现ICustomTypeDescriptor的类,由用户在PropertyGrid中查看和编辑。我的类还有一个IsReadOnly属性,它决定用户以后是否能够保存更改。我不想让用户进行更改,如果他们将无法保存。因此,如果IsReadOnly是真的,我想要覆盖任何属性,否则这些属性是可编辑的,仅在属性网格中读取。
我正在尝试使用GetProperties方法ICustomTypeDescriptor向每个PropertyDescriptor添加一个ReadOnlyAttribute。但它似乎不起作用。这是我的密码。
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
List<PropertyDescriptor> fullList = new List<PropertyDescriptor>();
//gets the base properties (omits custom properties)
PropertyDescriptorCollection defaultProperties = TypeDescriptor.GetProperties(this, attributes, true);
foreach (PropertyDescriptor prop in defaultProperties)
{
if(!prop.IsReadOnly)
{
//adds a readonly attribute
Attribute[] readOnlyArray = new Attribute[1];
readOnlyArray[0] = new ReadOnlyAttribute(true);
TypeDescriptor.AddAttributes(prop,readOnlyArray);
}
fullList.Add(prop);
}
return new PropertyDescriptorCollection(fullList.ToArray());
}这甚至是使用TypeDescriptor.AddAttributes()的正确方式吗?在调用之后进行调试时,AddAttributes()支柱仍然具有相同数量的属性,其中没有一个是ReadOnlyAttribute。
发布于 2011-11-28 21:07:43
TypeDescriptor.AddAttributes向给定的对象或对象类型添加类级属性,而不是属性级属性.最重要的是,除了返回的TypeDescriptionProvider的行为之外,我不认为它有任何影响。
相反,我将包装所有默认的属性描述符,如下所示:
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
return new PropertyDescriptorCollection(
TypeDescriptor.GetProperties(this, attributes, true)
.Select(x => new ReadOnlyWrapper(x))
.ToArray());
}其中ReadOnlyWrapper是这样一个类:
public class ReadOnlyWrapper : PropertyDescriptor
{
private readonly PropertyDescriptor innerPropertyDescriptor;
public ReadOnlyWrapper(PropertyDescriptor inner)
{
this.innerPropertyDescriptor = inner;
}
public override bool IsReadOnly
{
get
{
return true;
}
}
// override all other abstract members here to pass through to the
// inner object, I only show it for one method here:
public override object GetValue(object component)
{
return this.innerPropertyDescriptor.GetValue(component);
}
} https://stackoverflow.com/questions/2414717
复制相似问题