Bind to SelectedItems from DataGrid or ListBox in MVVM

SelectedItems is bindable as a XAML CommandParameter.

After a lot of digging and googling, I have finally found a simple solution to this common issue.

To make it work you must follow ALL the following rules:

  1. Following Ed Ball’s suggestion‘, on you XAML command databinding, define CommandParameter property BEFORE Command property. This a very time-consuming bug.

    enter image description here

  2. Make sure your ICommand‘s CanExecute and Execute methods have a parameter of object type. This way you can prevent silenced cast exceptions that occurs whenever databinding CommandParameter type does not match your command method’s parameter type.

    private bool OnDeleteSelectedItemsCanExecute(object SelectedItems)  
    {
        // Your code goes here
    }
    
    private bool OnDeleteSelectedItemsExecute(object SelectedItems)  
    {
        // Your code goes here
    }
    

For example, you can either send a listview/listbox’s SelectedItems property to you ICommand methods or the listview/listbox it self. Great, isn’t it?

Hope it prevents someone spending the huge amount of time I did to figure out how to receive SelectedItems as CanExecute parameter.

Leave a Comment