I am not sure whether is it possible to change attribute's parameter during runtime? For example, inside an assembly I have the following class
public class UserInfo
{
[Category("change me!")]
public int Age
{
get;
set;
}
[Category("change me!")]
public string Name
{
get;
set;
}
}
This is a class that is provided by a third party vendor and I can't change the code. But now I found that the above descriptions are not accurate, and I want to change the "change me" category name to something else when i bind an instance of the above class to a property grid.
May I know how to do this?
Well you learn something new every day, apparently I lied:
http://www.vsj.co.uk/articles/display.asp?id=713
I really don't think so, unless there's some funky reflection that can pull it off. The property decorations are set at compile time and to my knowledge are fixed
You can change Attribute values at runtime at Class level (not object):
You can subclass most of the common attributes quite easily to provide this extensibility:
There are more complex options that involve writing custom
PropertyDescriptor
s, exposed viaTypeConverter
,ICustomTypeDescriptor
orTypeDescriptionProvider
- but that is usually overkill.In case anyone else walks down this avenue, the answer is you can do it, with reflection, except you can't because there's a bug in the framework. Here's how you would do it:
All well and good, except that the category attribute is changed for all the properties, not just 'Age'.
In the mean time I've come to a partial solution, derived from the following articles:
Basically you would create a generic class
CustomTypeDescriptorWithResources<T>
, that would get the properties through reflection and loadDescription
andCategory
from a file (I suppose you need to display localized text so you could use a resources file (.resx
))