How do I access a subproperty from my .resw file in code?

16 Views Asked by At

How do I access "properties" of my .resw resource file in code?


For example, take this example RESW file (from MSDN):

screenshot of resw editor, with properties like 'Greeting.Text' and 'Farewell'

I can access Farewell easily:

auto resourceLoader{ Windows::ApplicationModel::Resources::ResourceLoader::GetForCurrentView() };
const auto myString = resourceLoader.GetString(L"Farewell");

But if I try to do the same thing with Greeting.Text (which automatically sets the Text property of a control with x:Uid="Greeting", so I can't change it), my app crashes:

auto resourceLoader{ Windows::ApplicationModel::Resources::ResourceLoader::GetForCurrentView() };
const auto myString = resourceLoader.GetString(L"Greeting.Text"); // crashes

Can I access this resource in code without duplicating it?

1

There are 1 best solutions below

0
citelao On BEST ANSWER

Yes you can!

Just replace the .s with /s:

auto resourceLoader{ Windows::ApplicationModel::Resources::ResourceLoader::GetForCurrentView() };
const auto myString = resourceLoader.GetString(L"Greeting/Text");

Further information

XAML calls resources that correspond to properties on a control property identifiers: whereas Farewell can only be loaded manually, from code, Greeting.Text corresponds to a property on a control (and is automatically applied to any control with the x:Uid="Greeting".

These property paths seem to be encoded as URIs, so you have to switch from . to / when accessing them in code.

MSDN describes that behavior on Localize strings in your UI and app package manifest#Refer to a string resource identifier from code:

If a resource name is segmented (it contains "." characters), then replace dots with forward slash ("/") characters in the resource name. Property identifiers, for example, contain dots; so you'd need to do this substitution in order to load one of those from code.

this.myXAMLTextBlockElement.Text = resourceLoader.GetString("Fare/Well"); // <data name="Fare.Well" ...> ...

If in doubt, you can use MakePri.exe to dump your app's PRI file. Each resource's uri is shown in the dumped file.

<ResourceMapSubtree name="Fare"><NamedResource name="Well" uri="ms-resource://<GUID>/Resources/Fare/Well">...