4

我有一个实现 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。

4

1 回答 1

3

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);
   }
}                
于 2011-11-28T21:07:43.753 回答