Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get selected ListView Item? [duplicate]

Tags:

c#

wpf

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".

like image 518
Sheamus Avatar asked Aug 21 '12 14:08

Sheamus


3 Answers

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.

like image 85
ie. Avatar answered Nov 05 '22 10:11

ie.


You can try with this code

var selectedItems = MyListView.SelectedItems;
foreach (ListViewItem selectedItem in selectedItems)
{
   //Treatment
}   
like image 35
Aghilas Yakoub Avatar answered Nov 05 '22 10:11

Aghilas Yakoub


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.

like image 3
Gerald Versluis Avatar answered Nov 05 '22 09:11

Gerald Versluis