WPF Listview Access to SelectedItem and subitems
listView1.SelectedItems[0]
returns an object
. You first need to cast it to its specific type before you can access its members. For casting you need to know the name of the class to cast to, but you're adding instances of an anonymous class (= has no name) to your ListView.
Solution: Define a class (e.g., Book
) with ISBN, Title and Author properties and add instances of Book
to the ListView. Then you can do the necessary cast:
private void getSelectedItem(object sender, MouseButtonEventArgs e)
{
Book book = (Book)listView1.SelectedItems[0];
System.Windows.MessageBox.Show(book.ISBN);
}
Don't forget to add instances if Book
to the ListView instead of instances of an anonymous type:
var items = from item in xdoc.Descendants("Book")
select new Book // <---
{
ISBN = (string)item.Element("ISBN"),
Title = (string)item.Element("Title"),
Author = (string)item.Element("Author"),
};
foreach (var item in items)
{
listView1.Items.Add(item);
}
Just wanted to be more clear with the code
Getting selected item
XAML:
<ListView Name="TheList" SelectionChanged="TheList_SelectionChanged"/>
CS:
private void TheList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MyItemClass SelectedItem = (MyItemClass)TheList.SelectedItem;
if (SelectedItem != null)
MessageBox.Show(SelectedItem.Title);
}
And for double clicking item (almost the same)
XAML:
<ListView Name="TheList" MouseDoubleClick="TheList_MouseDoubleClick"/>
CS:
private void TheList_SelectionChanged(object sender, MouseButtonEventArgs e)
{
MyItemClass SelectedItem = (MyItemClass)TheList.SelectedItem;
if (SelectedItem != null)
MessageBox.Show(SelectedItem.Title);
}