4

ICustomTypeDescriptorを実装し、PropertyGridでユーザーが表示および編集するクラスがあります。私のクラスには、ユーザーが後で変更を保存できるかどうかを決定するIsReadOnlyプロパティもあります。ユーザーが保存できない場合は、ユーザーに変更を許可したくありません。したがって、IsReadOnlyがtrueの場合、プロパティグリッドで読み取り専用になるように編集できるプロパティをオーバーライドしたいと思います。

ICustomTypeDescriptorのGetPropertiesメソッドを使用して、各PropertyDescriptorにReadOnlyAttributeを追加しようとしています。しかし、それは機能していないようです。これが私のコードです。

 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 に答える