如何从选定的ListView项中获取名称?

时间:2011-03-17 13:55:58

标签: c# wpf xml data-binding listview

我有一个ListView,带有一个数据绑定到TreeView的数据绑定,该数据绑定到XmlDataProvider。在ListView中,您可以一次选择多个项目。我的问题是我需要知道选择了哪些项目。如何从ListViewItems获取名称?

XAML:

<ListView x:Name="listViewCards" DataContext="{Binding ElementName=treeViewCategory, Path=SelectedItem}" ItemsSource="{Binding XPath=./card/title, UpdateSourceTrigger=PropertyChanged}" KeyDown="listViewCards_KeyDown" />

C#:

private void listViewCards_KeyDown(object sender, KeyEventArgs e)
{
    IList selectedListViewItems = listViewCards.SelectedItems;
    if (selectedListViewItems.Count > 1)
    {
        //delete all selected items from xml:
        foreach (XmlNode node in xmlNode.ChildNodes)
        {
            if (node.InnerText.Equals( ??? ))
            {
                //mark for deleting
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

  

类型的objekt   “System.Windows.Controls.SelectedItemCollection”   无法转换成   “System.Windows.Controls.ListViewItem”

试试这个:

private void listViewCards_KeyDown(object sender, KeyEventArgs e)
{
     IList selectedListViewItems = listViewCards.SelectedItems;
     if (selectedListViewItems.Count > 1)
     {
         //delete all selected items from xml:
         var collection = selectedListViewItems.Cast<XmlNode>();  //assuming your underlying data is XmlNode
         foreach(XmlNode node in collection)
         {
             //do whatever you want to do with node
             if (node.InnerText.Equals( ??? ))
             {
                 //mark for deleting
             }
         }
     }
}


相关:How to cast a System.Windows.Controls.SelectedItemCollection?

答案 1 :(得分:0)

listViewCards.SelectedItems;

将最有可能返回Type(ListViewItem)。如果类型为XmlNode,则需要转换该类型。

private void listViewCards_KeyDown(object sender, KeyEventArgs e)
{
    IList selectedListViewItems = listViewCards.SelectedItems;
    if (selectedListViewItems.Count > 1)
    {
        foreach(var node in ((ListViewItem)selectedListViewItems).Tag as XMLNode)
        {
            // Find your node in whatever type contains your xml
            // Do Some deleting or what have you.
        }
    }
}