But Wait!! I want to respond to the space bar in my Silverlight 2 ListBox!

by Scosby Wednesday, March 4, 2009

Assume you are registered for the KeyDown event on a ListBox control that contains a collection of CheckBoxes. You want to make your users' lives easier by letting them hit the space bar to toggle the CheckBox.IsChecked property you're in for a surprise!

If you're looking for an explanation of why you can't handle the Key.Space enumeration. According to Microsoft, "ButtonBase implements OnKeyDown in such a way that the SPACE key invokes a button click, but also sets Handled, which prevents SPACE from being reported as a KeyDown event that could be handled by a button instance". Obviously, ButtonBase has nothing to do with a ListBox, but we can see that depending upon the implementation of the OnKeyDown event, a class might not allow a specific event bubble up if the Handled property is set to true. This appears to be the case with the ListBox class as well. Since I cannot think of a reason for a ListBox (NOT an item) to not respond to the space bar, I don't mind changing this behavior.

So how do you get a ListBox to respond to the space bar? Well, young grasshopper, you must follow the Silverlight 2 way of creating your own class to function the way the base classes should. Create a class derived from ListBox and override OnKeyDown. In your derived class implementation, do NOT call the base class implementation all the time. Instead, set handled to false if the space key was pressed, for all other keys you should call the base class implementation. This allows the arrow keys to continue to function as you would expect.

protected override void OnKeyDown(KeyEventArgs e)
{
     switch (e.Key)
     {
           case Key.Space:
                 e.Handled = false;
                 break;

           default:
                 base.OnKeyDown(e);
                 break;
     }
}

Tags: , ,

Technology | Programming

blog comments powered by Disqus