【问题标题】:Setting Label Text in XAML to string constant将 XAML 中的标签文本设置为字符串常量
【发布时间】:2011-10-11 06:40:05
【问题描述】:

我有一个字符串常量,我必须在几个不同的 XAML 布局中重复使用它,所以我不想复制它,而只想将它绑定到一个常量。

我有一个在 C# 中定义字符串的类:

public static class StringConstants
{
     public static string MyString { get { return "SomeConstant"; } }
}

我希望能够通过 XAML 通过以下方式设置值:

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

这可以实现吗?我已经搜索了示例,但我只找到了涉及代码隐藏中一些修补的示例,我想知道是否有一个更简单的、仅限 XAML 的解决方案,如果我知道我只需要设置一次基于的值在一个永远不会改变的字符串值上。

【问题讨论】:

    标签: c# wpf xaml data-binding static-members


    【解决方案1】:

    您正在绑定到一个静态成员,因此您应该使用x:Static Markup Extension

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

    根据@H.B. 的评论,没有必要使用 Binding,所以使用起来更简单:

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

    【讨论】:

    • @H.B.你推荐什么?
    • @nonsensical101:把它排除在外:Content="{x:Static local:StringConstants.MyString}"
    • 不幸的是,这不适用于 UWP 应用。任何人都知道如何为那些人做这件事?
    • @H.B.您可能会使用绑定格式的字符串的一些原因。多重绑定,值转换
    【解决方案2】:

    将公共静态字符串 MyString 放入您的 App.xaml.cs。然后你可以参考如下。

        Content="{Binding Source={x:Static Application.Current}, Path=MyString}" 
    

    【讨论】:

      【解决方案3】:

      如果您在 非静态 类中有常量,则此方法不起作用。

      我用于绑定到 视图模型 (MVVM) 内部常量的解决方案。 它使用了一个 getter 属性,用于包装的代码更少。

      // view model
      public const string MyString = "abc";
      public string MyStringConst => MyString;
      

      .

      <!-- WPF -->    
      <Label Content="{Binding MyStringConst, FallbackValue='abc'}" />
      

      FallbackValue 用于设计器预览。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-14
        • 1970-01-01
        • 1970-01-01
        • 2021-11-27
        相关资源
        最近更新 更多