首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态地将ICustomTypeDescriptor.GetProperties返回的属性更改为只读

动态地将ICustomTypeDescriptor.GetProperties返回的属性更改为只读
EN

Stack Overflow用户
提问于 2010-03-10 05:22:35
回答 1查看 4.6K关注 0票数 4

我有一个实现ICustomTypeDescriptor的类,由用户在PropertyGrid中查看和编辑。我的类还有一个IsReadOnly属性,它决定用户以后是否能够保存更改。我不想让用户进行更改,如果他们将无法保存。因此,如果IsReadOnly是真的,我想要覆盖任何属性,否则这些属性是可编辑的,仅在属性网格中读取。

我正在尝试使用GetProperties方法ICustomTypeDescriptor向每个PropertyDescriptor添加一个ReadOnlyAttribute。但它似乎不起作用。这是我的密码。

代码语言:javascript
复制
 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。

EN

回答 1

Stack Overflow用户

发布于 2011-11-28 21:07:43

TypeDescriptor.AddAttributes向给定的对象或对象类型添加类级属性,而不是属性级属性.最重要的是,除了返回的TypeDescriptionProvider的行为之外,我不认为它有任何影响。

相反,我将包装所有默认的属性描述符,如下所示:

代码语言:javascript
复制
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
    return new PropertyDescriptorCollection(
        TypeDescriptor.GetProperties(this, attributes, true)
            .Select(x => new ReadOnlyWrapper(x))
            .ToArray());
}

其中ReadOnlyWrapper是这样一个类:

代码语言:javascript
复制
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);
   }
}                
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2414717

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档