Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF ListView - detect when selected item is clicked

Tags:

listview

wpf

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?

like image 426
scripni Avatar asked Apr 18 '12 10:04

scripni


2 Answers

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     } } 
like image 165
ChimeraObscura Avatar answered Sep 28 '22 00:09

ChimeraObscura


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)     {         ...     } } 
like image 41
lznt Avatar answered Sep 28 '22 02:09

lznt