WPF Listview Access to SelectedItem and subitems

后端 未结 3 2008
甜味超标
甜味超标 2020-12-07 00:30

Ok, I am having more problems with my C# WPF ListView control. Here it is in all its glory:



        
3条回答
  •  孤城傲影
    2020-12-07 01:16

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

提交回复
热议问题