How to get a string resource in C# (WPF)?

10,371

Solution 1

You need something like this:

var myText = this.FindResource("LocStrings") as string;

I guess, you can change this to wherever your resource is located.

UPDATE:

Usually, this is what I use for global resources:

var myText = Application.Current.FindResource("resourceName") as string;

Solution 2

Resource strings are accessible as static members in the auto-generated Resources class, found in <Default.app.namespace>.Properties.Resources. Properties and Resources are both unfortunate namespace names that clash with properties or namespaces that you probably already have in scope when writing WPF code. So you may have to use the fully-qualified name. e.g.

MyProject.Properties.Resources.AppName

for the string defined in Resources.resx with the name "AppName".

You should prefer this method of getting string resources over calling FindResource, as it provides compile-time checking of resource string names.

FFS. How can this not already be given as an answer, people?

Share:
10,371
Michel Keijzers
Author by

Michel Keijzers

I'm a professional software engineer, working at Altran. I have interest in OO languages and have C++/C# knowledge (MCTS, WinForm, WPF applications). Until recently, I wrote an app for Korg music synthesizers (PCG Tools) and try to learn myself WPF at the same time. Lately, I'm into Arduino/STM32, learning the basics (and more) of electronics, and trying to build a MIDI/DMX device for MIDI keyboards and DMX512 lighting devices.

Updated on June 30, 2022

Comments

  • Michel Keijzers
    Michel Keijzers almost 2 years

    I know how to get a resource from the string resource in XAML:

    {Binding OK, Source={StaticResource LocStrings}}
    

    However, I want to use a localized string in C# directly, e.g. something like

    someString = Resources["LocStrings"]["StringId"];
    

    But this does not compile.