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");?

Upvotes: 10

Views: 8744

Answers (4)

Taran
Taran

Reputation: 3221

use it simply

Properties.Resources.yourKey

Upvotes: -1

Shahin Dohan
Shahin Dohan

Reputation: 6922

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

Upvotes: 2

mcy
mcy

Reputation: 1258

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.

Upvotes: 4

dymanoid
dymanoid

Reputation: 15197

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"));

Upvotes: 13

Related Questions