1
votes

I have a ListBox which is bound to an ObservableCollection.

I want to select a ListBoxItem when the mouse is released (means MouseLeftButtonUp) and as well as I need to toggle the selection. Means when the ListBoxItem is selected, selecting the item again will deselect the item and vice versa.

When the ListBoxItem is selected I need to apply the different style as well.

I have tried as the following.

I have used the DataTemplate and Style for the ListBoxItem, in the EventSetter, I have subscribed the event for MouseLeftButtonUp and in the event handler I am selecting the item and toggling it.

The issue is there are number of ways to select the item(Ctrl+arrow keys, Shift+arrow keys, arrow keys, Ctrl+A) and applying the style for the selection.

I have used the 'Name' property to store the previous state of the ListBoxItem(Tag property already used for other purpose of the Data binding in the DataTemplate).

How can we achieve this?

Any idea will be greatly appreciated.

1

1 Answers

0
votes

The first thing I would suggest is forget using MouseLeftButtonUp and instead bind the control's SelectedItem to a variable in your code. That way if a user decides to use the keyboard everything is trapped.

<ListBox x:Name="lbItems" ItemsSource="{Binding Path=MyListItems}" SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay}"/> 

public ObservableCollection<YourClass> MyListItems
public YourClass SelectedItem

This automatically sets SelectedItem as soon as the user selects an item.

Then I would ask should the item deselect if they click it again? That's not standard behavior, do you need to deselect the item?

If you want to record the previously selected item, you could have a

private YourClass _previousSelectedItem;

private YourClass _selectedItem;
public YourClass SelectedItem
    {
     get { return _selectedItem;}
     set { if (_selectedItem == value) return;
           _previousSelectedItem = _selectedItem;
           _selectedItem = value;
         }
    }

Which you set when SelectedItem changes.

Does that give you some ideas?