title: WPF Binding UI events to commands in ViewModel
body: <p>I’m doing some refactoring of a simple application to follow MVVM and my question is how do I move a SelectionChanged event out of my code behind to the viewModel? I’ve looked at some examples of binding elements to commands but didn’t quite grasp it. Can anyone assist with this. Thanks!</p>
  
  <p><strong>Can anyone provide a solution using the code below? Many thanks!</strong> </p>
  
  <pre><code>public partial class MyAppView : Window 
  {
      public MyAppView()
      {
          InitializeComponent();
  
          this.DataContext = new MyAppViewModel ();
  
          // Insert code required on object creation below this point.
      }
  
      private void contactsList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
      {
          //TODO: Add event handler implementation here.           
          //for each selected contact get the labels and put in collection 
  
          ObservableCollection&lt;AggregatedLabelModel&gt; contactListLabels = new ObservableCollection&lt;AggregatedLabelModel&gt;();
  
          foreach (ContactListModel contactList in contactsList.SelectedItems)
          {
              foreach (AggregatedLabelModel aggLabel in contactList.AggLabels)
              {
                  contactListLabels.Add(aggLabel);
              }
          }
          //aggregate the contactListLabels by name
          ListCollectionView selectedLabelsView = new ListCollectionView(contactListLabels);
  
          selectedLabelsView.GroupDescriptions.Add(new PropertyGroupDescription("Name"));
          tagsList.ItemsSource = selectedLabelsView.Groups;
      }
  }
  </code></pre>