我有一个实现 ICustomTypeDescriptor 的类,并由用户在 PropertyGrid 中查看和编辑。我的班级还有一个 IsReadOnly 属性,该属性确定用户以后是否能够保存他们的更改。如果用户无法保存,我不想让他们进行更改。因此,如果 IsReadOnly 为真,我想覆盖任何在属性网格中可编辑为只读的属性。
我正在尝试使用 ICustomTypeDescriptor 的 GetProperties 方法将 ReadOnlyAttribute 添加到每个 PropertyDescriptor。但这似乎不起作用。这是我的代码。
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。