Getting Selected Item information from ListView in

2019-09-15 05:30发布

问题:

I have the following code which popualtes a ListView with photos from Flickr

 private async void ParseFlickrResponse(HttpResponseMessage response)
    {
        XDocument xml = XDocument.Parse(await response.Content.ReadAsStringAsync());          
        var photos = from results in xml.Descendants("photo")
                     select new FlickrImage
                     {
                         ImageId = results.Attribute("id").Value.ToString(),
                         FarmId = results.Attribute("farm").Value.ToString(),
                         ServerId = results.Attribute("server").Value.ToString(),
                         Secret = results.Attribute("secret").Value.ToString(),
                         Title = results.Attribute("title").Value.ToString()
                     };

        FlickrListView.ItemsSource = photos;
    }

I want to be able to then get source data for a individual item from this ListView to use elsewhere. However I can't seem to get anywhere with some of the commands. I'm new enough to C# and I don't know whether I should be using the SelectedItems, Items or SelectedIndex method to find which node my photo is stored in.

Any help would be great.

回答1:

You can use this piece of code:

EDITED: with SelectedItems

Dictionary<string, List<string>> dict =
    FlickrListView.SelectedItems
            .Cast<ListViewItem>()
            .ToDictionary(
                item => item.Text,
                item => item.SubItems
                            .Cast<ListViewItem.ListViewSubItem>()
                            .Select(subItem => subItem.Text)
                            .ToList());

OR

foreach (var item in FlickrListView.SelectedItems)
{
    FlickrImage obj = (FlickrImage) item;
    // ... do something ...
}