I'm using a WPF ListView control which displays a list of databound items.
<ListView ItemsSource={Binding MyItems}> <ListView.View> <GridView> <!-- declare a GridViewColumn for each property --> </GridView> </ListView.View> </ListView>
I'm trying to obtain a behavior similar to the ListView.SelectionChanged
event, only I want to also detect if the currently selected item is clicked. The SelectionChanged
event does not fire if the same item is clicked again (obviously).
What would be the best (cleanest) way to approach this?
Use the ListView.ItemContainerStyle property to give your ListViewItems an EventSetter that will handle the PreviewMouseLeftButtonDown event. Then, in the handler, check to see if the item that was clicked is selected.
XAML:
<ListView ItemsSource={Binding MyItems}> <ListView.View> <GridView> <!-- declare a GridViewColumn for each property --> </GridView> </ListView.View> <ListView.ItemContainerStyle> <Style TargetType="ListViewItem"> <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListViewItem_PreviewMouseLeftButtonDown" /> </Style> </ListView.ItemContainerStyle> </ListView>
Code-behind:
private void ListViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var item = sender as ListViewItem; if (item != null && item.IsSelected) { //Do your stuff } }
You can handle the ListView's PreviewMouseLeftButtonUp event. The reason not to handle the PreviewMouseLeftButtonDown event is that, by the time when you handle the event, the ListView's SelectedItem may still be null.
XAML:
<ListView ... PreviewMouseLeftButtonUp="listView_Click"> ...
Code behind:
private void listView_Click(object sender, RoutedEventArgs e) { var item = (sender as ListView).SelectedItem; if (item != null) { ... } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With