Динамическое изменение свойств, возвращаемых ICustomTypeDescriptor.GetProperties, только для чтения - PullRequest
4 голосов
/ 10 марта 2010

У меня есть класс, который реализует ICustomTypeDescriptor, и просматривается и редактируется пользователем в PropertyGrid. Мой класс также имеет свойство IsReadOnly, которое определяет, сможет ли пользователь сохранить свои изменения позже. Я не хочу позволять пользователю вносить изменения, если они не смогут сохранить. Поэтому, если IsReadOnly имеет значение true, я хочу переопределить любые свойства, которые в противном случае были бы доступны для редактирования в сетке свойств.

Я пытаюсь использовать метод GetProperties ICustomTypeDescriptor, чтобы добавить атрибут 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.

1 Ответ

3 голосов
/ 29 ноября 2011

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