2

With C#6, using the nameof() keyword, it it now possible to create a type safe Display attribute that makes use of localization. (see also DisplayName attribute from Resources?)

The result will be something like this:

    [Display(NameRes = Localization.Account.MinPasswordLength), ResourceType = typeof(Localization.Account))]
    public int MinPasswordLength { get; set; }

But, after typing this for dozens of properties, I get the feeling there must be an easier way. Each time I am typing the same information twice (almost).

My question is this: How do I create a custom DisplayName attribute that infers the ResourceType from the Name information?

The code then would look something like this:

    [Display(NameResource = Localization.Account.MinPasswordLength)]
    public int MinPasswordLength { get; set; }

Any idea if this is possible? And if so: How?

Community
  • 1
  • 1
Frank
  • 431
  • 1
  • 5
  • 25
  • If you check the definition of `DisplayAttribute` class you will notice that it is `sealed` which means you can not inherit from it. One way would be to create your custom `DisplayNameAttribute` that will read the information from the resource file. – Davor Zlotrg Sep 06 '16 at 21:34
  • Yes, the class is sealed. That's unfortunate, but maybe it might be accomplished with an extension? – Frank Sep 20 '16 at 09:00

1 Answers1

0

One way could be to define another attribute that just define take the resource type.

You put this attribute into the class definition. And during the resource search you will inspect the type host to determine the resources type.

Example :

[DisplayResourceHost(typeof(Localization.Account))]
public class ViewModel
{
    [Display(NameResource = Localization.Account.MinPasswordLength)]
    public int MinPasswordLength { get; set; }
}
Mickael Thumerel
  • 516
  • 4
  • 14