10

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

1
  • Welcome to SO. Please take a moment and read this topic to get informed whether you should use tags in titles or not. I'd recommend to read all of these topics too.
    – dymanoid
    Commented Jan 26, 2015 at 8:50

4 Answers 4

13

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"));
3
  • But you loose support for strong typed MyProject.Properties.Resources.SignInBtn access.
    – xmedeko
    Commented May 21, 2015 at 7:44
  • 3
    You should change the Resources to the file name of the resource file you use. For example Strings which is used in the examples. Commented May 2, 2016 at 8:14
  • GetCallingAssembly can produce for you unwelcome results if u don't take care stackoverflow.com/a/12912473/7429464 Commented Nov 29, 2017 at 13:27
4

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.

1
  • 1
    Passing null results in a NullReferenceException
    – user585968
    Commented Aug 7, 2018 at 5:04
2

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

use it simply

Properties.Resources.yourKey

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.