将XAML中的标签文本设置为字符串常量 [英] Setting Label Text in XAML to string constant

查看:151
本文介绍了将XAML中的标签文本设置为字符串常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单一的字符串常量,我必须在几个不同的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:静态标记扩展

You are binding to a static member so you should use x:Static Markup Extension:

<Label Content="{Binding Source={x:Static local:StringConstants.MyString}}"/>

根据@ HB的评论,没有必要使用Binding,因此使用起来更简单: p>

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆