It's easy to set a Button's background color in XAML:
Wiring it up with a name and a click event-handler makes it easy to change that color in code:
But that would grow tedious if you wanted to set a lot of buttons or other controls, particularly if you wanted to set them all to the same color. Fortunately, there's a way for any number of them to rely on a shared setting you only have to change once for the change to be made to them all.
First, you define a named "resource," like this:
Line 2 gives this resource its name, "interiorColor" (you can pick any name you like). To use it, you replace the Button's Background property with a reference to the resource, like this:
Note that the Background value is still enclosed in double-quotes. Now the XAML compiler knows it must look up the value by finding the resource named "interiorColor." Because we want to be able to change it at run time, we have declared this to be a "DynamicResource," as opposed to a "StaticResource," which is fixed for the run of the application.
In our click event-handler, instead of setting the Button's background color, we'll look up and change the setting of our resource:
Note that "Resources" is a property of the Window that encloses the Button, not a property of the Button itself. Note also that "Item" is a property of the Resources property (which is a ResourceDictionary object). And finally, note that the Item property is indexed by the "interiorColor"
string, used as a key. (Okay,
really finally, note that the item, once you've looked it up, is assigned a new SolidColorBrush object, not just a color; WPF fills regions with brushes, which have colors, not with the colors themselves.)
Now, when we click the button, the resource value changes. And, any element with a property set to that resource is updated with the change. That means we can have several Buttons, all sharing that resource, which all change when the resource changes:
The Buttons defined in Lines 1 and 2, above, will change color when that first Button we defined above is clicked. Note that the Button created at Line 3 refers to "interiorColor" as a static resource. This means it will
not change color. This illustrates an important characteristic of resources: a resource is not, by itself, either static or dynamic. Rather,
references to those resources are either static or dynamic, with static references looking up the value once, and dynamic references monitoring the value for changes, and updating their elements when a change is detected.
Next, I'll show how more than one attribute of an element can be grouped into a set, again shared by multiple elements, and how to deal with elements that have some, but not all, of their attributes in common.