Setting Label Text in XAML to string constant

荒凉一梦 提交于 2019-11-27 23:40:26

问题


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.

I have a class which defines the string in C#:

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

I'd like to be able to set the value through XAML via something like the following:

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

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.


回答1:


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

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

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}"/>



回答2:


Put the public static string MyString in your App.xaml.cs. Then you can reference it as follows.

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



回答3:


In the case that you have a constant inside of a non-static class, this doesn't work.

My solution for binding to a constant inside of a view model (MVVM). It uses a getter property with less code for wrapping.

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

.

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

The FallbackValue is used for the Designer preview.



来源:https://stackoverflow.com/questions/6794274/setting-label-text-in-xaml-to-string-constant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!