wpf ListView - 从所选项目中获取列值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21421815/
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
ListView - Grabbing a column value from the selected item
提问by user1189352
I'm trying to avoid databinding as i don't understand it and need to get this finished.. but everything I'm trying doesn't seem to work. For example i'd like to print out the 2nd column of the selected item.. but everything I see on google says to use SubItems when mine doesn't have one for some reason?
我试图避免数据绑定,因为我不理解它并且需要完成它......但我正在尝试的一切似乎都不起作用。例如,我想打印出所选项目的第二列..但是我在谷歌上看到的所有内容都说当我的由于某种原因没有子项目时使用子项目?
<ListView Name="myListView" MouseDoubleClick="myListView_MouseDoubleClick_1">
<ListView.View>
<GridView>
<GridViewColumn Header="H1" DisplayMemberBinding="{Binding Col1}"/>
<GridViewColumn Header="H2" DisplayMemberBinding="{Binding Col2}"/>
<GridViewColumn Header="H3" DisplayMemberBinding="{Binding Col3}"/>
</GridView>
</ListView.View>
</ListView>
private void Button_Click_1(object sender, RoutedEventArgs e)
{
myListView.Items.Add(new { Col1 = "test1", Col2 = "Test2", Col3 = "test3" });
}
private void myListView_MouseDoubleClick_1(object sender, MouseButtonEventArgs e)
{
//THIS DOESN'T WORK, SubItems doesn't exist?
myListView.SelectedItems[0].SubItems[0].Text.ToString();
}
回答by har07
Try to cast SelectedItemto specific type. After that you'll be able to access full set of the item's properties. Since you have anonymous type here, try to cast it to dynamic:
尝试强制转换SelectedItem为特定类型。之后,您将能够访问该项目的全部属性。由于您在这里有匿名类型,请尝试将其转换为dynamic:
var selectedItem = (dynamic)myListView.SelectedItems[0];
MessageBox.Show(selectedItem.Col3);
回答by donmichael
For me, it worked like this:
对我来说,它是这样工作的:
myListView.SelectedItems[0].SubItems[1].Text;
However, I fill the listview from sql database. You just create items, but no subitems. Here is the reference, how to create:
但是,我从 sql 数据库填充了列表视图。您只创建项目,但没有子项目。这是参考,如何创建:
https://msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.subitems(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.windows.forms.listviewitem.subitems(v=vs.110).aspx

