views:

948

answers:

3

I have a ListBox control that I want to change into having a toggle selection. i.e. Click once on an item selects it, click again it deselects it. Also, clicking another item in the list should do the default action of deselecting the previous item and selecting the new one.

What's the best way of achieving this?

A: 

I would keep the standard ListBox as that way you will keep the default behaviour you want, then for deselecting an item could you just handle it in the mouse down event? i.e. use something like this:

Point newPoint = e.GetPosition(backgroundImage);

HitTestResult result = VisualTreeHelper.HitTest(this, newPoint);

if (result.VisualHit is ListBoxItem)

I'm not sure if this is the best way, the only other way I would go about doing this is to derive my own ListBox from the standard windows control and add in a dependency property to allow me to handle the deselection in the style. If you want to take this approach I shouldn't remove the default behaviour you want to keep either, I used this approach to create a ListBox that would display an image next to the text.

If you need any pointers on where to start, then just give me a shout.

Bijington
+2  A: 

What you want is a RadioButtonList. You can create one by creating an ItemDataTemplate and put a RadioButton inside it. Then you can modify the template of the RadioButton to looks like a button.

sacha
A: 

I've managed to achieve this myself by slightly creating two custom classes, ToggleListBox & ToggleListBoxItem. There are a couple of handy overrides (the most important in ToggleListBox is the one which creates your ListBoxItem).

From there it was easy to handle clicking on the same item twice, or pressing the space / enter key. 40 lines of code for both classes and works fine.

Mark Ingram