Charles Petzold



Three-Way Switch Demo in XAML

September 15, 2007
Roscoe, N.Y.

We drove up to the house in Roscoe for the weekend and discovered that the ceiling light in the kitchen no longer worked. We quickly established that the circuit breaker hadn't tripped (other stuff on the same line still worked) and the three bulbs hadn't burned out at the same time. The next items to check would be the fixture itself and the wall switches.

What made this troubleshooting job just a little bit more challenging is that the ceiling light in the kitchen is controlled by two "three-way" wall switches, one at each entrance to the kitchen. These switches don't have on and off positions: If the light is off, flipping either switch turns it on, and then flipping either switch turns it off. (The kitchen isn't that large — the switches are only about 9-feet apart — but one of the entrances to the kitchen is from the basement stairs, so the switch there is really convenient.)

I wondered if one broken three-way switch would affect the whole system, and then much to my shock, I realized that I didn't know how three-way switches worked! This ignorance was particularly shameful because I had once written an entire book about how logic gates could be built from electrical relays, and how these logic gates could be combined into adders, flip-flops, and an entire computer. But I knew the three-way switch didn't rely on relays. It had to be simpler than that!

Three-way switches are called that because they have three connections, a common and two lines. From my childhood immersion in things electrical, I knew this configuration as a single-pole double-throw (SPDT) switch. Apparently in British electrical circles, it's known as a two-way switch. The line connectors of the two switches are connected in parallel as this little XAML file demonstrates:

Three-Way Switch screenshot

ThreeWaySwitch.xaml

When you run the XAML file, click either switch to flip it. Red means that electricity is flowing (the same convention used in that book I alluded to earlier).

The XAML file is built around two templates defined within styles: one to turn a CheckBox into a three-way switch, and the other to turn a Control into an entire wiring diagram. Once these styles and templates are defined in the Resources section, the entire thing is rendered with a simple (and unusual):

Turning some sub-elements from black to red required two MultiTrigger elements. I was particularly pleased how simple they turned out to be, mostly because I appropriated the Foreground property of Control for this purpose, and used TemplateBinding markup extensions to bind the Foreground property of the two switches, and the Stroke property of many of the Path elements used for the wiring.

The problem in the kitchen turned out to be the fixture. When we took it down and reconnected the twist connectors, it worked.