4

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.

Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119

3 Answers3

6

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;
NoOne
  • 3,851
  • 1
  • 40
  • 47
  • Exists there no better (type-safe) way? With WinForms app getting string resource was much better: Properties.Resources.ResourceName; – hfrmobile Nov 24 '15 at 10:19
  • None that I am aware of. But you can always check the type yourself. – NoOne Nov 24 '15 at 20:34
  • It is also possible to use .resx files in a WPF app to get that benefits but I wonder that XAML doesn't provide such benefits... – hfrmobile Nov 26 '15 at 20:23
  • 1
    AppNamespace.Properties.Resources.. A Fundamental WPF thing! – Robin Davies May 11 '20 at 01:31
  • @RobinDavies I don't use RESX files with WPF, only resource dictionaries. Right now I am not sure if your suggestion would work (it has been some years since I last checked those kind of things), but the way the question was formed, I had the impression the author wanted to get the translation based on a key of type `string`. – NoOne May 11 '20 at 16:00
3

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?

Robin Davies
  • 7,547
  • 1
  • 35
  • 50
0

This is not a complete answer but maybe could helps in your internationalization application, see this codeplex article maybe will be useful to you.

Raúl Otaño
  • 4,640
  • 3
  • 31
  • 65