How to bind multiple selection of listview to viewmodel?

后端 未结 9 2125
刺人心
刺人心 2020-12-13 09:14

I am implementing a listview, and a button next to it. I have to be able that when i select multiple items in a listview, and then click on a button, then the selected items

9条回答
  •  轮回少年
    2020-12-13 09:54

    Like Doctor has already pointed out, you can bind SelectedItems to 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 goes here
      }
      
      private bool OnDeleteSelectedItemsExecute(object SelectedItems)
      {
          // Your 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.

提交回复
热议问题