DarinH
DarinH

Reputation: 4879

Unselecting a WP7 listbox item on click

I've seen similar questions asked about WPF, but none of the proposed solutions seem to work under Windows Phone 7.

Basically, I've got a listbox where the behavior needs to be 1) when user taps an item in the list, it's selected. 2) when user taps any other item, the first is unselected and the tapped item is selected (so far this is just normal single select list box behavior) 3) when user taps an already selected item, the item "unselects" (so that there is no selected item at all anymore).

It's certainly easy enough to intercept the MouseLeftButtonDown event and clear the selection, but the ui system appears to continue processing the tab and turns around an reselects the item I've just unselected.

At first, I thought binding could be the problem, and the list items +are+ bound to an observableCollection, but neither the "selectedItem" or "selectedIndex" are bound at all.

I tried setting the event args handled prop to true:

e.Handled = true

but no change.

Any ideas?

Upvotes: 0

Views: 2015

Answers (1)

1adam12
1adam12

Reputation: 984

Use MouseLeftButtonUp() rather than MouseLeftButtonDown().

    private object _selected;

    private void ListBox_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        var list = (ListBox) sender;

        if (list.SelectedItem == _selected)
        {
            list.SelectedIndex = -1;
            _selected = null;
        }
        else
        {
            _selected = list.SelectedItem;
        }
    }

Upvotes: 3

Related Questions