xaml 中作为资源键的字符串值

string value as resource key in xaml

在我的 WPF 解决方案中,我创建了一个自定义翻译标记扩展。我使用输入的键作为要显示的默认语言字符串。当用户更改语言时,我只是将资源绑定值更新为翻译版本。 如果最终用户不想使用多种语言并且他不想维护单独的资源文件,这真的很不错。

问题是我无法用 "" 包围密钥。 这意味着如果字符串中存在逗号,则它会被解释为多个键。我通过在键周围包裹特殊 "" 解决了这个问题:

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

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

如果我想在text/key中加上逗号,语法真的很乱。颜色突出显示也很疯狂。

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

有没有其他方法可以在 XAML 编辑器不会发疯并且我不需要在键前后添加特殊 " 的情况下编写内联键?

有一个非常简单的解决方案可以解决您的问题:将字符串用单引号引起来 (')。您需要了解的有关如何处理标记扩展的所有信息都可以在 in this MSDN article.

中找到

要点:

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.

所以你可以这样写:

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

如果你想完全去掉任何类型的引号,你当然可以求助于像这样的 hacky 解决方法:

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

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

// etc.

那当然可能会弄乱你的空格,不幸的是 MarkupExtensions 不能使用 params 关键字,所以你必须为任意数量的逗号添加构造函数。