Thursday, June 12, 2008

Getting Selection and Arrow keys to behave right with a ListBox in the.NET Compact Framework

I had a form in a Window Mobile application that contains a Label and a ListBox. I wanted the ListBox to behave according to the Windows Mobile UI guidelines where you click on an item with the stylus and it is automatically selected. I used the SelectedIndexChanged event to implement this behavior and it worked fine when an item was selected with the stylus. However, with all of the different kinds of devices, many of them have partial or even full keyboards and at the very least they have a joypad or equivalent, my users were wanting to use the arrow keys to navigate to a specific item in the list and then press the enter button (never using the stylus). Unfortunately, the SelectedIndexChanged event is fired anytime the ListBox’s selected item is change (by stylus or keys) and since using the arrow keys usually requires scrolling through several items before getting to the item you want, the next item in the list is always selected (be it the one you want or not). I could not find a way in the .NET Compact Framework to get the ListBox to work like I wanted.

My solution was to replace the ListBox with a ListView. Change the View property to Details and change the Activation property to OneClick. Then use the ItemActivate event provided by the ListView instead of the SelectedIndexChanged event. You also have to add at least one Column to the ListView, and you can optionally set HeaderStyle to None to get rid of the column header and make the ListView look just like a ListBox.

No comments: