我有一个字符串常量,我必须在几个不同的 XAML 布局中重复使用它,所以我不想复制它,而是想将它绑定(bind)到一个常量。
我有一个在 C# 中定义字符串的类:
public static class StringConstants
{
public static string MyString { get { return "SomeConstant"; } }
}
我希望能够通过类似以下内容的 XAML 设置值:
<Label Content="{Binding local:StringConstants.MyString}"/>
这可以实现吗?我已经搜索了示例,但我只找到了涉及代码隐藏中一些修补的示例,我想知道是否有更简单的、仅 XAML 的解决方案,如果我知道我只需要设置一次值在一个永远不会改变的字符串值上。
最佳答案
您正在绑定(bind)到一个静态成员,因此您应该使用 x:Static
Markup Extension :
<Label Content="{Binding Source={x:Static local:StringConstants.MyString}}"/>
根据@H.B. 的评论,没有必要使用 Binding,因此使用起来更简单:
<Label Content="{x:Static local:StringConstants.MyString}"/>
关于c# - 将 XAML 中的标签文本设置为字符串常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6794274/