Changing a property's attribute at runtime is generally frowned upon.
After all, attributes are just metadata and should remain unchanged after they are compiled.
But sometimes you have to do it, regardless of what the "best practices" are saying.
In my project, there are a lot of tree view items share the same entity. But now the user want to add more properties for one of the view item. And we have to use the original entity because of business limits.
So we added these requested properties and display them in that view item. However, as you can image, all of other view items also displays this newly added properties.
We are not going change this in view layer. So the only choice would be change the attribute at runtime.
The attribute we are using is "BrowsableAttribute", which under namespace System.ComponentModel
Take below entity for example, we are going to hide "Customer" property...
public class Task
{
public int TaskID { get; set; }
...
public string Customer { get; set; }
}
And here is the code to set "Browsable" attribute to false, the default value is true.
var descriptor = TypeDescriptor.GetProperties(typeof(DisplayWorkflowTask))["Customer"];
var attribute = (BrowsableAttribute) descriptor.Attributes[typeof (BrowsableAttribute)];
var attributeFieldInfo = attribute.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
if(attributeFieldInfo != null) attributeFieldInfo.SetValue(attribute, false);
Yap, here we are.