6

Possible Duplicate:
WPF Listview Access to SelectedItem and subitems

I have a listview in my xaml and I want to get the selected item in the code-behind. In fact I would like to get the content of the item (which is an object). I've tried to do MyListView.SelectedItems[0] but it doesn't work, I have "accessor get or set expected".

Community
  • 1
  • 1
Sheamus
  • 223
  • 1
  • 5
  • 15

3 Answers3

4

I guess you should use SelectedItem not SelectedItems:

This property is meant to be used when SelectionMode does not equal Single. If the selection mode is Single the correct property to use is SelectedItem.

ie.
  • 5,982
  • 1
  • 29
  • 44
3

You can try with this code

var selectedItems = MyListView.SelectedItems;
foreach (ListViewItem selectedItem in selectedItems)
{
   //Treatment
}   
Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51
3

How are you using it? It should be MyListView.SelectedItems[0].

MyObject foo = (MyObject)MyListView.SelectedItems[0];

You should probably add some checks if SelectedItems contains actual items and the SelectedItem object is indeed a MyObject, but you get the idea.

Also if you select a single item there is SelectedItem, I think.

Gerald Versluis
  • 30,492
  • 6
  • 73
  • 100