views:

361

answers:

0

I have a class which implements ICustomTypeDescriptor, and is viewed and edited by the user in a PropertyGrid. My class also has a IsReadOnly property which determines if the user will be able to save their changes later. I don't want to allow the user to make changes if they will not be able to save. So if IsReadOnly is true I want to override any properties that would otherwise be editable to be read-only in a property grid.

I'm trying to use the GetProperties method of ICustomTypeDescriptor to add a ReadOnlyAttribute to each PropertyDescriptor. But it doesn't seem to be working. Here's my code.

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

Is this even the correct way to use TypeDescriptor.AddAttributes()? While debuging after the call the AddAttributes() prop still has the same number of attributes none of which are a ReadOnlyAttribute.