Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a string as a static resource

Tags:

wpf

xaml

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.

like image 533
Marcom Avatar asked Apr 14 '11 09:04

Marcom


4 Answers

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> 
like image 176
Felice Pollano Avatar answered Sep 28 '22 08:09

Felice Pollano


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}” /> 
like image 40
Henrik Avatar answered Sep 28 '22 08:09

Henrik


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>
like image 24
Damascus Avatar answered Sep 28 '22 06:09

Damascus


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}"
like image 37
bafsar Avatar answered Sep 28 '22 06:09

bafsar