Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use wpflocalizeextension in Code-Behind?

How can I use wpflocalizeextension in C# code? In xaml, for getting a localized string I can use it as follows:

<Window x:Class="SomeClass"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:lex="http://wpflocalizeextension.codeplex.com"    
    lex:LocalizeDictionary.DesignCulture="uk-UA"    
   lex:ResxLocalizationProvider.DefaultAssembly="DesktopApp"    
   lex:ResxLocalizationProvider.DefaultDictionary="Resources">
   <Button Content="{lex:Loc SignInBtn}"/>

How can I get a localized string in code, for example MessageBox.Show("SignInBtn");?

like image 858
Тарас Красниця Avatar asked Jan 25 '15 15:01

Тарас Красниця


3 Answers

This is pretty simple. The localization keys are stored as AssemblyName:Resources:KeyName, where Resources is the Resources class name, typically you won't change it to something other.

You can create a simple wrapper to get localized values:

using WPFLocalizeExtension.Extensions;

public static class LocalizationProvider
{
    public static T GetLocalizedValue<T>(string key)
    {
        return LocExtension.GetLocalizedValue<T>(Assembly.GetCallingAssembly().GetName().Name + ":Resources:" + key);
    }
}

So assuming you have created your string resource with the "SignInBtn" key, you can just call:

MessageBox.Show(LocalizationProvider.GetLocalizedValue<string>("SignInBtn"));
like image 98
dymanoid Avatar answered Nov 15 '22 16:11

dymanoid


I regularly use the following native command and have not encountered any errors yet:

LocalizeDictionary.Instance.GetLocalizedObject("keyComesHere", null, LocalizeDictionary.Instance.Culture).ToString()

Of course, before casting to string, you should check for null values.

like image 20
mcy Avatar answered Nov 15 '22 16:11

mcy


mcy's answer worked somehow at first, but later I was getting nulls.

I would prefer to use the 3rd overload to make sure I get the right resource:

LocalizeDictionary.Instance.GetLocalizedObject("AssemblyName", "DictionaryName", "Key", LocalizeDictionary.Instance.Culture);
like image 37
Shahin Dohan Avatar answered Nov 15 '22 17:11

Shahin Dohan