IS there a way to define a constant string to be used as a static resource across the whole application?
I am running a Wpf application but there is no main xaml form. The application is a collection of xaml controls handled by a single classic .cs form.
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>
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}” />
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>
You can use like this:
First, sample constant variable:
namespace Constants
{
public class ControlNames
{
public const string WrapperGridName = "WrapperGrid";
}
}
And second XAML using:
<TextBlock Text="{x:Static Member=Constants:ControlNames.WrapperGridName}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With