Use static resources to customize a XAML program

interlocked boxes

This example shows how you can use static resources to customize a XAML program. The previous example Use static resources to draw three interlocked boxes using XAML and C# uses static resources to avoid duplicating code. This example uses static resources to make it easier to configure an application.

This example adds the following three resources to the Window‘s Resources section.

<!-- Define the cubes' colors. -->
<SolidColorBrush x:Key="Brush1" Color="Yellow" />
<SolidColorBrush x:Key="Brush2" Color="Fuchsia" />
<SolidColorBrush x:Key="Brush3" Color="Cyan" />

Later, the boxes use those resources to define the boxes’ materials. The following code shows how the example creates its first box. The code that refers to the brush resource is shown in blue.

<!-- Box 1 -->
<GeometryModel3D Geometry="{StaticResource CubeGeometry}">
        <ScaleTransform3D ScaleX="1" ScaleY="2" ScaleZ="3" />

        <DiffuseMaterial Brush="{StaticResource Brush1}" />

The code for the other boxes is similar.

This technique doesn’t save you any code. In fact, it makes the code slightly more complicated because you need to define and refer to the brushes instead of simply typing “Red” for a material’s brush. However, it makes it easier for you to configure the program. If you decide to change the boxes’ colors, you can do it in the Resources section at the top of the program instead of needing to dig through the code to find the places where you need to make the changes.

This is sort of like creating a const at the beginning of a C# program and then using it to customize the program.

If you used a brush multiple times (for example, if the program drew 10 red boxes, 10 green boxes, and 10 blue boxes), then the resources would make it even easier to perform all of the changes correctly. You would only need to change each brush once (a total of 3 changes) to update all of the boxes (a total of 30 boxes).

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in graphics, wpf, XAML and tagged , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.