7

I'd like to access resources directly in my xaml layout, and official doc give us some poor examples so I can't get it work. Suppose following Resources.resw :

enter image description here

I can access my string resources from C# class like so:

 var loader = new ResourceLoader();
 var resourceString = loader.GetString("txt_ok");

How can I access this resource in xaml for a TextBlock text for example?

<TextBlock
  x:Name="MyTextBox"
  Text="I want to get string resource here"/> 

I was trying some examples from here or here but no succes

Community
  • 1
  • 1
Choletski
  • 7,074
  • 6
  • 43
  • 64
  • 1
    When you use x:Static as explained in the linked solutions, do you get compilation errors? If so, maybe you need to make your resx public (open properties and set custom tool = PublicResXFileCodeGenerator). – heringer Mar 21 '16 at 12:23
  • I get error `Static is not supported in a Windows Universal project.` when try it like: `Text="{x:Static MyAppName.Properties.Resource.txt_ok}"` – Choletski Mar 21 '16 at 12:28
  • If you (or further readers) are still looking for a solution that can be re-used across other (asp.net/xamarin/wpf) projects and/or only want to use the `Text` property to bind to resources, check out this: https://stackoverflow.com/a/35813707/2901207 – CularBytes Sep 26 '19 at 16:02

2 Answers2

12

In UWP app, when you define a string resource in your resource file, the Name property of this string can be either "Name" or "Name.Property".

In xaml code, we use Uid attribute to associate controls to resource, but when we use resource in xaml code, we must add the specified property to the resource's name, in case the control don't know what property should be applied to the string resource.

This is the same in the code behind, you get the resource using

 var loader = new ResourceLoader();
 var resourceString = loader.GetString("txt_ok"); 

but you still need to set this resourceString to the Text property of a TextBlock for example:

txt.Text = resourceString;

So if you want to use the string resource directly in xaml code, you will need to edit your resource file like this:

enter image description here

And you can now associate your TextBlock to your resource like this:

<TextBlock x:Uid="txt_cancel" />

Or like this (not 100% correct, it depends on the location of your resource file):

<TextBlock x:Uid="/Resources/txt_settings" />

Addition: You can also define other property in your resource file for example like this:

enter image description here

And when you apply this resource for a TextBlock:

<TextBlock x:Uid="MyApp" />

You will see:

enter image description here

Grace Feng
  • 16,564
  • 2
  • 22
  • 45
1

Access string resource property in c# code

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

https://liftcodeplay.com/2015/11/08/accessing-resource-strings-via-code-in-uwp/

Minute V
  • 25
  • 3