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ではありません。