I am having a problem with the following code:
//This class can't be changed for is part of an EF data context.
public partial class person
{
public string Name { get; set; }
}
//I have this partial just to access the person DisplayNameAttribute
[MetadataType(typeof(person_metaData))]
public partial class person
{
}
//And this is the MetaData where i am placing the
public class person_metaData
{
[DisplayName("Name")]
public string Name { get; set; }
}
How do i get the DisplayNameAttribute when it is in another class? Thank's in advance!
Assuming the AssociatedMetadataTypeTypeDescriptionProvider
for your class has been registered correctly, the System.ComponentModel.TypeDescriptor
class will honour the attributes from your metadata class.
Add this somewhere near the start of your program:
TypeDescriptor.AddProvider(
new AssociatedMetadataTypeTypeDescriptionProvider(typeof(person)),
typeof(person));
Then access the properties:
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(person));
PropertyDescriptor prop = properties["Name"];
string displayName = prop.DisplayName;
Alternatively, you can use the AssociatedMetadataTypeTypeDescriptionProvider
class directly:
var provider = new AssociatedMetadataTypeTypeDescriptionProvider(typeof(person));
ICustomTypeDescriptor typeDescriptor = provider.GetTypeDescriptor(typeof(person), null);
PropertyDescriptorCollection properties = typeDescriptor.GetProperties();
PropertyDescriptor prop = properties["Name"];
string displayName = prop.DisplayName;
NB: Your DisplayName
attribute doesn't currently change the display name, so you won't see any difference. Change the value passed to the attribute constructor to see that the type descriptor is working.