XAML binding goodness

If you’re wondering why you should make the move to WPF, I’d like to share a little sample that demonstrates just how powerful WPF databinding really is, and how you can use it to bind to things that aren’t as obvious. In this sample, we’re going to create a status bar that shows whether certain keys are enabled or not. These are the Insert, Scroll Lock, Num Lock and Caps Lock keys that have their status displayed in applications like Word.

In order to perform this “magic”, we need to use a bit of the Windows API to get the state of the keys we are interested in. We use the GetKeyState API call in user32.dll, with an enumeration mapping the values we’re interested in.

The trick to actually reacting to the changes lies in previewing the keyup event, which allows you to intercept events from the keyboard (without changing them), and update the status of the keys accordingly. As we expose the keyboard items we are interested in as properties, using Change notification

Now that we have the keymanager in place, physically performing the binding is childs play.

There – I hope I’ve whetted your appetite, and got you interested in exploring data binding in WPF.


One thought on “XAML binding goodness

  1. Jean-Michel Bezeau

    You could have done this without the Windows API calls, since the framework is offering its own methods:

    ‘ NumLock handling:
    If System.Windows.Input.Keyboard.IsKeyToggled(Key.NumLock) Then
    IsNumPressed = “NUM”
    IsNumPressed = “”
    End If

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s