Setting Label Text in XAML to string constant

一世执手 提交于 2019-11-29 09:31:41

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

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

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.

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