mtlynch
mtlynch

Reputation: 3553

Setting Label Text in XAML to string constant

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.

Upvotes: 16

Views: 23726

Answers (3)

Beauty
Beauty

Reputation: 965

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.

Upvotes: -1

Navid Rahmani
Navid Rahmani

Reputation: 7958

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

Upvotes: 33

paparazzo
paparazzo

Reputation: 45096

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

Upvotes: 0

Related Questions