[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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}"> <GeometryModel3D.Transform> <ScaleTransform3D ScaleX="1" ScaleY="2" ScaleZ="3" /> </GeometryModel3D.Transform> <GeometryModel3D.Material> <DiffuseMaterial Brush="{StaticResource Brush1}" /> </GeometryModel3D.Material> </GeometryModel3D>

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.