C# 如何获取选定的 ListView 项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12057093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 20:14:41  来源:igfitidea点击:

How to get selected ListView Item?

c#wpf

提问by Sheamus

Possible Duplicate:
WPF Listview Access to SelectedItem and subitems

可能重复:
WPF Listview 访问 SelectedItem 和子项

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

我的 xaml 中有一个列表视图,我想在代码隐藏中获取所选项目。事实上,我想获取项目的内容(这是一个对象)。我试过 MyListView.SelectedItems[0] 但它不起作用,我有“访问器获取或设置预期”。

回答by Aghilas Yakoub

You can try with this code

您可以尝试使用此代码

var selectedItems = MyListView.SelectedItems;
foreach (ListViewItem selectedItem in selectedItems)
{
   //Treatment
}   

回答by Gerald Versluis

How are you using it? It should be MyListView.SelectedItems[0].

你如何使用它?应该是MyListView.SelectedItems[0]

MyObject foo = (MyObject)MyListView.SelectedItems[0];

You should probably add some checks if SelectedItemscontains actual items and the SelectedItemobject is indeed a MyObject, but you get the idea.

如果SelectedItems包含实际项目并且SelectedItem对象确实是 a MyObject,您可能应该添加一些检查,但您明白了。

Also if you select a single item there is SelectedItem, I think.

此外,如果您选择单个项目SelectedItem,我认为。

回答by ie.

I guess you should use SelectedItemnot SelectedItems:

我想你应该使用SelectedItem而不是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.

此属性旨在在 SelectionMode 不等于 Single 时使用。如果选择模式为 Single,则要使用的正确属性是 SelectedItem。