I need to add an attribute to some property in runtime (for design-time purposes). I know I can do this for classes:
TypeDescriptor.AddAttributes(typeof(MyType), new MyRuntimeAttribute());
But I can't find any way to do the same for properties.
Any suggestions?
UPD: The exactly task is following:
public class BaseClass {
public BaseClass(string name) { Name = name; }
public Name { get; set; }
}
public class Descendant1: BaseClass {
public Descendant1() : base("Default Name 1") { }
}
...
public class DescendantN: BaseClass {
public DescendantN() : base("Default Name N") { }
}
I want each of the descendants to have each own DefaultValueAttribute at the Name property with the corresponding default name. And I don't want to hardcode DefaultValueAttribute on each descentand :)
You can't dynamically add or remove attributes. Note that TypeDescriptor doesn't actually add an attribute to the class either: If you check the array that typeof(MyType).GetCustomAttributes(false)
returns after you attach your attribute with MyRuntimeAttribute you'll notice that it isn't part of it.
Since you mention design-time, what you can do is dynamically modify attributes. Is that what you actually want to do?
See also:
You can also provide a control designer and in that designer you can override PreFilterProperties. While typically this is used to hide properties, it can also be used to add them.
http://www.codeproject.com/KB/webforms/HidingProperties.aspx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.