0

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).

kyrylomyr
  • 12,192
  • 8
  • 52
  • 79
user1765862
  • 13,635
  • 28
  • 115
  • 220

1 Answers1

0

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.

Sheridan
  • 68,826
  • 24
  • 143
  • 183