title: WPF: How to bind a command to the ListBoxItem using MVVM?
body: <p>I have just started learning MVVM. I've made the application from scratch by following this <a href="http://www.c-sharpcorner.com/UploadFile/yougerthen/474/" rel="noreferrer">MVVM tutorial</a> (I highly recommend it to all MVVM beginners out there). Basically, what I have created so far is a couple of text boxes where user adds his or her data, a button to save that data which subsequently populates the ListBox with all entries made. </p>
  
  <p>Here's where I got stuck: I want to be able to double-click on a ListBoxItem and to trigger a command that I have created and added to my ViewModel. I don't know how to finish the XAML side, i.e. I don't know how to bind that command to the ListBox(Item). </p>
  
  <p>Here's XAML: </p>
  
  <pre><code>...
  &lt;ListBox 
      Name="EntriesListBox" 
      Width="228" 
      Height="208" 
      Margin="138,12,0,0" 
      HorizontalAlignment="Left" 
      VerticalAlignment="Top" 
      ItemsSource="{Binding Entries}" /&gt;
  ...
  </code></pre>
  
  <p>Here's ViewModel: </p>
  
  <pre><code>public class MainWindowViewModel : DependencyObject
  {
      ...
      public IEntriesProvider Entries
      {
          get { return entries; }
      }
  
      private IEntriesProvider entries;
      public OpenEntryCommand OpenEntryCmd { get; set; }
  
      public MainWindowViewModel(IEntriesProvider source)
      {
          this.entries = source;
          ...
          this.OpenEntryCmd = new OpenEntryCommand(this);
      }
      ...
  }
  </code></pre>
  
  <p>And finally, here's the OpenEntryCommand that I want to be executed once the user double-clicks the item in the EntriesListBox:</p>
  
  <pre><code>public class OpenEntryCommand : ICommand
  {
      private MainWindowViewModel viewModel;
  
      public OpenEntryCommand(MainWindowViewModel viewModel)
      {
          this.viewModel = viewModel;
      }
  
      public event EventHandler CanExecuteChanged
      {
          add { CommandManager.RequerySuggested += value; }
          remove { CommandManager.RequerySuggested -= value; }
      }
  
      public bool CanExecute(object parameter)
      {
          return parameter is Entry;
      }
  
      public void Execute(object parameter)
      {
          string messageFormat = "Subject: {0}\nStart: {1}\nEnd: {2}";
          Entry entry = parameter as Entry;
          string message = string.Format(messageFormat, 
                                         entry.Subject, 
                                         entry.StartDate.ToShortDateString(), 
                                         entry.EndDate.ToShortDateString());
  
          MessageBox.Show(message, "Appointment");
      }
  }
  </code></pre>
  
  <p>Please help, I'd appreciate it. </p>