3

I want to translate property. I have two resources files: DataResource.resx and DataResource.en.resx. There are NameString string(both). My property:

[DisplayName("NameString")]
public virtual string Name { get; set; }

I have used this solution for localization DataDisplay attribute.

public class LocalizedDisplayNameAttribute: DisplayNameAttribute
{
    public LocalizedDisplayNameAttribute(string resourceId) 
        : base(GetMessageFromResource(resourceId))
    { }

    private static string GetMessageFromResource(string resourceId)
    {
        // TODO: Return the string from the resource file
    }
}

But I don't understand what I must to write in GetMessageFromResource method.
Thanks.

Community
  • 1
  • 1
user348173
  • 8,818
  • 18
  • 66
  • 102

1 Answers1

3

For your custom DataAnnotations attribute your need to write following code in your GetMessageFromResource method:

private static string GetMessageFromResource(string resourceId)
{
    var propertyInfo = typeof(DataResource).GetProperty(resourceId, BindingFlags.Static | BindingFlags.Public);
    return propertyInfo.GetValue(null, null);
}

This code should do the job assuming you have an error in your question and there are should be LocalizeDisplayNameAttribute, not the DisplayName one:

[DisplayName("NameString")]
public virtual string Name { get; set; }

Anyway I recommend using of lambda accessors for getting localized strings from resources so you can rename/navigate them using your refactoring tool.

Eskat0n
  • 937
  • 9
  • 21
  • I think I hurried a little with advice to use lambdas since anyway DisplayName attribute itself can't take lambda as constructor's parameter. Forget about it. – Eskat0n Aug 24 '11 at 17:04
  • I am using this approach, instead of resource file, i am getting data from database. When I hard coded , it works, but I need user to select the language. So I had a dropdown and I need to change the language when the user changes the dropdown. ie, from Display name attribute I need to pass the locale,how can I achieve this ? – kbvishnu Oct 19 '12 at 10:33
  • Also How can I implement localization in buttons. tooltip etc ? – kbvishnu Oct 23 '12 at 11:07
  • You can just use static properties of statis resource class which contains string literals you want to localize in your application – Eskat0n Oct 26 '12 at 07:55