【问题标题】:Dynamically change properties returned by ICustomTypeDescriptor.GetProperties to readonly将 ICustomTypeDescriptor.GetProperties 返回的属性动态更改为只读
【发布时间】:2010-03-10 05:22:35
【问题描述】:

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

【问题讨论】:

    标签: c# .net propertydescriptor icustomtypedescriptor getproperties


    【解决方案1】:

    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);
       }
    }                
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-21
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 2013-07-01
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      相关资源
      最近更新 更多