Changing attributes values at runtime

by brogge 9. February 2009 23:11

This post adds some remarks to the excellent post of David Morton on 'Changing attribute parameters at runtime', which can be read at http://blog.davemorton.net/2008/10/changing-attribute-parameters-at.html.

I am trying to hide some properties for my object when it is loaded into the property grid. When I applied the method put forward in David's post it didn't seem to solve my problem. In fact, all properties dissappeared from the property grid.

I have done some research and found out that David his method only seems to be working when the property is actually annotated in the code. So changing the read only property did not work for the following property: 

[Category("Document template")]
[
DisplayName("Description")]
[
Description("Description of the document.")]
public override string Description
{
  
get { return base.Description; }
  
set { base.Description = value; }
}

while it did work on this version of the code:

[Category("Document template")]
[
DisplayName("Description")]
[
Description("Description of the document.")]
[Browsable(true)]
public override string Description
{
  
get { return base.Description; }
  
set { base.Description = value; }
}

When retrieving the attribute information using the following code, both produced the same result:

PropertyDescriptor namePropertyDescriptor = TypeDescriptor.GetProperties(this)["Description"];
BrowsableAttribute attrib = (BrowsableAttribute)namePropertyDescriptor.Attributes[typeof(BrowsableAttribute)];
FieldInfo isReadOnly = attrib.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);

However, when setting the value to for the attribute to 'false', the result was different. When using the first code snippet all properties of the object dissapeared, while the second code snippet made it work.

I don't have an exact explanation for this (yet) but will add it to this post as soon as I find one. In the meantime, annotating the code with the attribute seems to solve my problem.

Hope this helps !

Currently rated 2.0 by 1 people

  • Currently 2/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

Comments

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen