Windows 10 UWP

Accessing resource strings via code in UWP

I’ll demonstrate how to access strings defined in your resources via code.

Background

If you are writing a multi-lingual application or just want to have a central store of all your string resources, the use of resw is the way to go. The concept has been around for ages. In UWP we have resw files.

If you are using resw, you then hook up the resource strings to your UI using the x:Uid tag.

Sample strings from resw
Sample strings from resw

If we wanted to use the DeleteBlock.Text on a label, it would look something like this. Note that it automatically applies the text to the .Text property. As such, you could

<TextBlock x:Uid="DeleteBlock" />

As an aside, I highly recommend the use of the Multi-lingual App Toolkit. It allows you to easily manage your translations and can use Bing and pre-existing Microsoft translations to help translate strings in your app.

Accessing strings via Code

You need to access the ResourceLoader class. It’s relatively straightforward – first get the resources for the current view and then call GetString. I collected the resource loader via code behind on my main page.

var res = ResourceLoader.GetForCurrentView();
var deleteText = res.GetString("DeleteBlock/Text");
var confirmYes = res.GetString("ConfirmYes");

If you want to access a string such as DeleteBlock.Text you cannot put a period. Instead, put a /

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s