Defining “Constants”

I briefly mentioned in Chapter 2 that strings and other simple BCL (Base Class Library) types could potentially be defined as resources in XAML, but we didn't investigate the topic further at the time. Let's take a look at how we can define strings and other BCL types as resources in XAML. (We'll refer to these as constants.) For example, uses for this technique include maintaining common values in a theme file, and supporting localization in your application by maintaining a set of strings in resource dictionaries, which you can merge when appropriate with your application's resources.

images Note Only a limited number of types from the System namespace can actually be declared in XAML. For example, you cannot define a DateTime using this method.

The first step is to declare a namespace prefix to the System namespace in the root element of your XAML file where the constant is to be defined, like so:

xmlns:sys="clr-namespace:System;assembly=mscorlib"

You can then declare the constants (as resources) using the types in that namespace:

sys:String x:Key="OKText">OK</sys:String>

images Note You can declare these constants as you would any other resources, adding them to the Resources property of any element in the object hierarchy. A constant can then be used by any control below that element in the object hierarchy. Alternatively, you can define the constants in a resource dictionary, and merge it into the object hierarchy where required.

You can then use the StaticResource markup extension to make use of the constant:

<Button Content="{StaticResource OKText}" />

images Note When assigning the constant to a content property, such as in the preceding example, you must use attribute syntax rather than content element syntax, as discussed in Chapter 2.

Let's put it all together in a simple example:

<UserControl x:Class="Chapter10Sample.Views.ConstantsExample"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <UserControl.Resources>
        <sys:String x:Key="OKText">OK</sys:String>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot">
        <Button Content="{StaticResource OKText}" />
    </Grid>
</UserControl>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset