0
votes

I'm developing an UWP app which will be side loaded and get's most of its config from an WebAPI. I want to be able to use translated labels both in XAML and Code, as I see the "UWP way" is to use resource files, but I don't want to store the string in the project itself, I want them to load from the WebAPI and then use the cached key-value distionary.

Obviously no problem to get the strings in code, problem is with XAML - in WPF it was pretty simple with a custom MarkupExtension, but because we don't have MakrupExtensions in UWP, is there a clean way to do so?

EDIT:

What I tried so far:

  • create base class for all controls with an object that has an indexer to get a translations - not working because x:Bind doesn't support string based indexers
  • trying to use custom dynamic object - not working because x:Bind doesn't support dynamic objects
  • trying to ass some own class as a resource and access properties from it - again not working

For now the only way seems to create a huge class where each translation/label will have to have it's own property, or to use standard Binding (or some class derived from it).

EDIT_2:

Forgot, that another use case would be to use it in xaml resources with templates, not only controls and pages.

1

1 Answers

0
votes

Ok it looks like I found a solution, by using the CustomResource feature as described here:

https://msdn.microsoft.com/en-us/windows/uwp/xaml-platform/customresource-markup-extension

if I implement a class like this:

public class MyResourceLoader : CustomXamlResourceLoader
{
    protected override object GetResource(string resourceId, string objectType, string propertyName, string propertyType)
    {
        return "Translation for key:" + resourceId;
    }
}

And initialize it in the App.xaml.cs constructor:

public App()
{
    CustomXamlResourceLoader.Current = new MyResourceLoader();
    this.InitializeComponent();
    this.Suspending += OnSuspending;
}

Then I can access it from XAML in following way:

<TextBlock Text="{CustomResource myTranslationKey}"></TextBlock>

And it works.

However... the XAML designer in VisualStudio doesn't understand the CustomResource markup extension and underlines it as an error with a Cannot resolve symbol 'CustomResource' message. But it compiles and works, so have to be good enough for now.