WPF Listview Access to SelectedItem and subitems

≯℡__Kan透↙ 提交于 2019-11-28 01:50:23

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);
}
    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);
}

I have got an issue with code above, once I use it, my listView did not list any of those values. I do not know if that will help you or if that is correct but after a few tests I added () after "select new Book" and then ListView could show all fields correctly for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!