For a recent C# side-project, I found myself wanting to use an editable ListBox control, with intuitive keyboard shortcuts for rapid data-entry. The model I had in mind was similar in appearance to the VC++ Directories pane in Visual Studio's Options dialog, adding support for Tab and Shift+Tab navigation between items in the list. Trawling round the web, I found plenty of candidates for re-use, but none of them really had the look and feel I was after. So I took the opportunity to educate myself about .NET User Controls and started work on a new side-side-project.
As it turns out, implementing a basic User Control is pleasingly simple. Visual Studio has a wizard that generates the boilerplate code and from there it is straightforward to use the design view to position any constituent parts in much the same way as you would for a Windows Form. In the case of my EditableListBox, those components were a normal ListBox, a TextBox to act as the edit field and some Button instances to enable user-invoked sorting, ordering, addition and removal of items. I took the icons for the buttons from Everaldo Coelho's Crystal icons project.
The next step was to add appropriate keyboard event handlers so that the control presented the smooth data-entry experience that I envisaged. I opted to display the edit field in place over an item when that item is double-clicked, or when Enter or Space are pressed and the item is selected. Tab and Shift+Tab can then be used to navigate through the listed items, confirming any changes that are made, whereas the up and down cursor keys perform similarly, but will discard changes. The editing mode can be left by pressing Enter, to confirm changes, or Escape, which discards changes.
Event handlers were also added for each of the buttons, so that the control could be operated with the mouse as it could with the keyboard. The most noteworthy of these was the sort button, which actually led to two different sorting algorithms being implemented. When the button is pressed, a quicksort is used to order the items with typical O (n log n) performance. However, when a new item is added to an already sorted list, it is only necessary to bubble that item up or down to its correct position.
With the event handlers in place, all that remained was to expose a set of public properties from the control, so that end-users could customise its appearance and behaviour to match their requirements.
For anyone interested in looking at or re-using the source code, I've pushed the source up to GitHub under an MIT license. I've also uploaded a built DLL containing the control, for anyone that simply wants to re-use it in their own project verbatim.




0 comments:
Post a Comment