PETZOLD BOOK BLOG

Charles Petzold on writing books, reading books, and exercising the internal UTM


Recent Entries
< PreviousBrowse the ArchivesNext >
Subscribe to the RSS Feed

8-Bit Binary Adder in XAML

June 10, 2006
Roscoe, NY

"It's such a fine line between stupid and clever." — David St. Hubbins, musician.

And, this, I'm afraid, falls on the stupid side. It's an 8-bit binary adder realized entirely in XAML:

BinaryAdder.xaml

Click on a digit to toggle it between 0 and 1.

This XAML file mostly demonstrates the power of templates, which are objects that let you change the entire visual appearance of controls, and can also respond to property changes.

The file defines three templates. One template makes CheckBox controls display the digit 0 and 1 based on the IsChecked property. The CheckBoxBit.xaml file shows this template in isolation. The template is defined by a resource and then used with three CheckBox controls. Click on the digits to toggle them.

A second template in BinaryAdder.xaml defines a column of digits and performs the one-bit addition logic. I've done something similar (but less extensive) in the AndGates.xaml file, which defines a template using two CheckBox controls and one TextBlock to simulate a two-input AND gate. This template uses the CheckBox controls with their default templates so they look like normal controls, but obviously the templates in CheckBoxBit.xaml could be used to render the CheckBox controls as binary digits.

Each column of bits in the BinaryAdder.xaml file is a separate control based on a template similar to the one in AndGates.xaml but obviously more extensive. Each column has three inputs (the two CheckBox bits in the column and Carry In) and two outputs (the TextBlock sum and Carry Out).

As usual when designing adders, the problem of the Carry overwhelms everything else. Since each column of digits in BinaryAdder.xaml is a control, I knew each one needed a binding to implement the Carry. The target of the binding would be the Carry In property and the binding source would be the Carry Out property of the next less significant bit. If I were coding these controls, I would surely define two Boolean properties named CarryIn and CarryOut, but I had to make do with the properties I had.

My solution was to appropriate two existing Boolean properties that I could alter without affecting the control too much. (IsVisible, for example, would have been a poor choice.) I used Focusable for Carry In and ForceCursor for Carry Out. It's certainly not a general solution, but for those of us obsessed with taking XAML to the limits, it works.


Recent Entries
< PreviousBrowse the ArchivesNext >
Subscribe to the RSS Feed

(c) Copyright Charles Petzold
www.charlespetzold.com