How to use wpflocalizeextension in Code-Behind?
Asked Answered
M

4

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

Mithgarthr answered 25/1, 2015 at 15:6 Comment(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.Supposing
S
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"));
Supposing answered 26/1, 2015 at 8:38 Comment(3)
But you loose support for strong typed MyProject.Properties.Resources.SignInBtn access.Forecourt
You should change the Resources to the file name of the resource file you use. For example Strings which is used in the examples.Deadlock
GetCallingAssembly can produce for you unwelcome results if u don't take care https://mcmap.net/q/1162745/-why-is-my-method-calling-assembly-getcallingassembly-not-jit-inlinedBasanite
G
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.

Guest answered 5/5, 2015 at 12:33 Comment(1)
Passing null results in a NullReferenceExceptionCallable
P
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);
Porterporterage answered 22/1, 2018 at 15:41 Comment(0)
K
-1

use it simply

Properties.Resources.yourKey

Kura answered 1/2, 2019 at 19:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.