将 XAML 中的标签文本设置为字符串常量 [英] Setting Label Text in XAML to string constant
问题描述
我有一个字符串常量,我必须在几个不同的 XAML 布局中重新使用它,因此我不想复制它,而是将它绑定到一个常量.
I have a single string constant that I have to re-use in several different XAML layouts, so instead of duplicating it, I'd like to just bind it to a constant.
我有一个在 C# 中定义字符串的类:
I have a class which defines the string in C#:
public static class StringConstants
{
public static string MyString { get { return "SomeConstant"; } }
}
我希望能够通过 XAML 通过如下方式设置值:
I'd like to be able to set the value through XAML via something like the following:
<Label Content="{Binding local:StringConstants.MyString}"/>
这能实现吗?我已经搜索了示例,但我只找到了涉及对代码隐藏进行一些修补的示例,我想知道是否有更简单的 XAML 解决方案,如果我知道我只需要设置一次基于的值在一个永远不会改变的字符串值上.
Is this achievable? I've searched for examples, but I've only found samples that involve some tinkering in the code-behind and I'm wondering if there's a simpler, XAML-only solution if I know that I just need to set the value once based on a string value that will never change.
推荐答案
您正在绑定到静态成员,因此您应该使用 x:Static
标记扩展:
You are binding to a static member so you should use x:Static
Markup Extension:
<Label Content="{Binding Source={x:Static local:StringConstants.MyString}}"/>
根据@H.B. 的评论,没有必要使用 Binding,因此使用起来更简单:
According to @H.B.'s comment it's not necessary to use Binding so it's simpler to use:
<Label Content="{x:Static local:StringConstants.MyString}"/>
这篇关于将 XAML 中的标签文本设置为字符串常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!