tags:

views:

71

answers:

2

Hi all,

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 :)

+1  A: 

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:

Korbinian
Sorry, but no.I've just investigate a little and now I think that TypeConverter implementation with GetProperties override is that what I need (PropertyDescriptorAdaptor will return modified AttributesCollection; based on http://msdn.microsoft.com/en-us/library/system.componentmodel.propertydescriptor.aspx article). I'll post here a results after some tests.However, thank you for the second link, answer posted there is very interesting.
Beresta
A: 

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

Tergiver