1

Possible Duplicate:
Binding SelectedItems of Listview

I have a ListView and User can select multiple items. I need to get list of items selected from ListView in my View Model.

please suggest to get SelectedItems from ListView.

Thank you

Community
  • 1
  • 1
Harsha
  • 1,861
  • 7
  • 28
  • 56
  • There is a blog post addressing this problem: http://blog.functionalfun.net/2009/02/how-to-databind-to-selecteditems.html – ekholm Aug 22 '12 at 09:05

1 Answers1

2

There are two ways I usually do this

If I only need to know what is selected for the purpose of a command, I will setup my RelayCommand or DelegateCommand in the ViewModel to expect a parameter of type IList<SomeClass> and pass the ListView.SelectedItems in as the CommandParameter

<Button Command="{Binding SomeCommand}"
        CommandParameter="{Binding ElementName=MyListView, Path=SelectedItems}" />

The other method I often use is to create an IsSelected property on whatever data item is being used in the ListView, and bind it to the ListViewItem.IsSelected property

<Style TargetType="{x:Type ListViewItem}">
    <Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>

Then my ViewModel can find out if an item is selected or not by looking at it's IsSelected property

foreach(var item in MyCollection)
{
    if (item.IsSelected)
        // Do work
}
Rachel
  • 130,264
  • 66
  • 304
  • 490