Donnerstag, 27. Oktober 2011

The Silverlight ListBox and the space bar

I have, as I think, a quite common scenario: I have a ListBox control containing items that have a checkbox. I want to enable the user to remove items using the delete key and to toggle the checkbox using the spacebar.

So I set up a little MVVM magic to bind the keydown event of the listbox to my view model. Everything is working fine for the delete key. But when it comes to space, I never reached my command handler. It could not be an issue with the command binding, because it worked for delete.

So I searched around and found out that I was not the only one having recognized the issue. The post I found was from 2009 and written about Silverlight 2. I am wondering why this behaviour has not been changed because it seems hardly reasonable to me.

The technical reason for this behavior is, that within the ListBox control in the OnKeyDown method, if the pressed key is space, the Handled flag of the event parameters is set to true, so the space bar press will not propagate upwards the visual tree.

The solution is easy: inherit your custom ListBox control, overwrite the OnKeyDown method, handle the space press and set Handled to false:


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

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

Lucky you, if you already have your custom control project in place...

Keine Kommentare:

Kommentar veröffentlichen