jsandv
jsandv

Reputation: 306

string value as resource key in xaml

In my WPF solution I have created a custom translate markup extension. I am using the inputed key as the default language string to display. When user changes language I just update the resource binding value to the translated version. This is really sweet if end-user does not want to have multiple languages and he does not want to maintain separate resource file.

The problem is that I can't surround the key with "". This means that if a comma exists in the string then it was interpreted as multiple keys. I solved that by wrapping special "" around the key:

&quot;  <!-- Double quote symbol -->

https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/how-to-use-special-characters-in-xaml

The syntax is really messy if I want to have comma in the text/key. Also color highlighting goes wild.

<Label Content="{l:Translate Some kind of string}"/>
<Label Content="{l:Translate &quot;With comma, not causing trouble if quoted&quot;}"/>

Is there any other way to write the key inline where the XAML editor does not go crazy and I don't need to add special " in front of key and after key?

Upvotes: 0

Views: 522

Answers (1)

Manfred Radlwimmer
Manfred Radlwimmer

Reputation: 13394

There is a very easy solution to your problem: Wrap your string in single quotes ('). Everything you need to know about how Markup Extensions are processed can be found in this MSDN article.

The gist of it:

The text value of either a MEMBERNAME or STRING is read as follows. Leading whitespace characters are consumed without being represented in the generated token. If the first non-whitespace character is a quote (either Unicode code point 0022, Quotation Mark, or 0027, Apostrophe), the tokenizer proceeds as follows:

The first quote is consumed and is not represented in the token’s value.

The text value becomes the characters up to but not including the next matching quote (i.e. a character of the same code point as the opening quote) that is not preceded by a “\” character. All these characters and also the closing quote are consumed. Any “\” characters in the resulting text value are removed.

Whitespace characters following the closing quote are consumed, and are not represented in the token.

So you can just write it like this:

<Label Content="{l:Translate 'With comma, not causing trouble if quoted'}"/>

If you want to get rid of any kind of quotes altogether, you could of course resort to a hacky workaround like this:

public TranslateExtension(string value1, string value2)
{
    _value = value1 + ", " + value2;
}

public TranslateExtension(string value1, string value2, string value3)
{
    _value = value1 + ", " + value2 + ", " + value3;
}

// etc.

That would of course potentially mess up your whitespaces and unfortunately MarkupExtensions can't utilize the params keyword, so you would have to add constructors for any number of commas.

Upvotes: 1

Related Questions