Getting WPF ListView.SelectedItems in ViewModel
.net, data-binding, listview, mvvm, wpf
Solution
To get the `SelectedItems` only when a command is executed then use `CommandParameter` and pass in the `ListView.SelectedItems`.
<ListBox x:Name="listbox" ItemsSource="{Binding StringList}" SelectionMode="Multiple"/>
<Button Command="{Binding GetListItemsCommand}" CommandParameter="{Binding SelectedItems, ElementName=listbox}" Content="GetSelectedListBoxItems"/>
Problem
There are some posts discussing adding data-binding ability for `ListView.SelectedItems` with non-trivial amount of code. In my scenario I don't need to set it from the `ViewModel`, just getting selected items in order to perform action on them and it is triggered by command so push update is also not necessary. Is there a simple solution (in terms of lines of code), maybe in code-behind? I am fine with code-behind as long as `View` and `ViewModel` don't need to reference each other. I think this is a more generic question: "best practice for VM to get data from the View on-demand", but I can't seem to find anything...