简体   繁体   中英

Double click on selected ListBox item

I have listbox with items from observablecollection.

 <ListBox Name="listBoxData"
          DataContext="{Binding Source={StaticResource MainWindowViewModelDataSource}}" 
          ItemTemplate="{DynamicResource BookTemplate}"                                 
          ItemsSource="{Binding Books, UpdateSourceTrigger=PropertyChanged}" 
          SelectedItem="{Binding SelectedBook, Mode=TwoWay}">

Question is how to wire double click action on selected item?

I do not avoid code behind approach (which is currently empty, all my logic is inside mvvm).

Your final line is a little confusing... to me, it says 'a code behind solution is ok', but then you mention MVVM, so I'm not sure. Either way, here is a simple answer for you. Declare the ListBox :

<ListBox SelectionChanged="ListBox_SelectionChanged" />

And then in the code behind, assuming single selection mode:

private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ListBoxItem listBoxItem = (ListBoxItem)e.AddedItems[0];
    listBoxItem.PreviewMouseDoubleClick += ListBoxItem_PreviewMouseDoubleClick;
    listBoxItem = (ListBoxItem)e.RemovedItems[0];
    listBoxItem.PreviewMouseDoubleClick -= ListBoxItem_PreviewMouseDoubleClick;
}

private void ListBoxItem_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    // Selected item was double clicked
}

If you want the MVVM way, then you can just move the code from the ListBox_SelectionChanged handler to the SelectedBook setter and the ListBoxItem_PreviewMouseDoubleClick handler to the view model. However, it's not such a good idea handling UI events in the view model. It's better to use Attached Properties to handle them for you, but that's another story.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM