WPF String Static Resources


When you are working in XAML you may find that you’d like to have a way to declare a constant that you can use throughout your XAML code. For example you may have an app that uses an Opacity of 0.5 for several controls. In your XAML code, you have Opacity=”0.5″. You can change that to Opacity=”{StaticResource MyOpacity}” throughout your XAML code and set the value of 0.5 in a static resource. How do you do that?

In the title of this post I have used the word String. However, the example below is actually a Double. The 0.5 needs to be declared as a Double in the resource, even though it ends up as a string in the XAML code, as in Opacity=”0.5″.

Below is the XAML code.

    <Window.Resources>
        <clr:Double x:Key="MyOpacity">0.5</clr:Double>
    </Window.Resources>

Below is an example of the application of the static resource we’ve defined.

<TextBlock Margin="10" Opacity="{StaticResource MyOpacity}" Text="Hello"></TextBlock>