Define a string as a static resource

You can define it as an application resource:

 <Application x:Class="xxxxxx"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:clr="clr-namespace:System;assembly=mscorlib"
                 StartupUri="MainWindow.xaml">
        <Application.Resources>
            <clr:String x:Key="MyConstString">My string</clr:String>
        </Application.Resources>
    </Application>

Just add a resource dictionary XAML file, let's say it's named Dictionary.xaml (Visual Studio can create you one automatically)

Then, add your static resource in this dictionary.

To finish, reference the dictionary in all your XAML controls:

<UserControl.Resources>
                <ResourceDictionary Source="Dictionary.xaml"/>
    </UserControl.Resources>

Supplemantary to the answer by @FelicePollano - for code indentation to work I put this as a separate 'answer'.

If you happen to have your original constant defined in a .cs-file you can avoid duplicating its value in <Application.Resources> by this:

<x:Static x:Key="MyConstString" Member="local:Constants.MyString" />

For the reference local above to work you need to include the namespace xmlns:local="clr-namespace:Utils" in the tag <Application>.

The cs-class could then look like this:

namespace Utils 
{
    public class Constants
    {
        public const string MyString = "My string";
    }
}

An example on usage in the xaml-code could then be:

<TextBlock Text="{StaticResource MyConstString}" />

Tags:

Wpf

Xaml