使用for循环而不是foreach循环遍历wpf列表框

时间:2014-06-05 14:27:03

标签: c# wpf listbox

我有一个c#wpf列表框,我正在尝试从所选项目中获取值。我不能使用foreach循环(我找到的每个值都会从列表框中删除一个项目)。但这似乎不可能。

我想要的是这样的事情:

for (int i = <numberofselecteditems> - 1; i >= 0; i--)
{
    string displaymembervalue = listbox.selecteditem[i].displaymembervalue;

}

我有一个解决方案,涉及两次遍历所有列表框项目。这不是一个真正的选择,因为它会使应用程序放慢太多。

就像我之前说的那样,这不是

System.Windows.Forms.Listbox

但是

System.Windows.Controls.Listbox
谢谢!!

学家

4 个答案:

答案 0 :(得分:1)

参见解决方案here,它实际上是以一种方式使用foreach:

foreach (var item in listBox1.SelectedItems)
{
    // Do what you want here... Console.WriteLine(item), etc.
}

如果您真的想使用for循环而不是foreach,请执行以下操作:

for(int i = selectedItems.Count - 1; i >= 0; --i)
{
    var item = selectedItems[i];
    // Do what you want with item
}

答案 1 :(得分:1)

这是绑定到Observable集合的XAML

  <ListBox ItemsSource="{Binding items}"/>

这是您可观察的对象集合

private ObservableCollection<Object> _items;

public ObservableCollection<Object> items{
  get{ return _items; }
}

以下是对它们的枚举以及每个项目的删除

for(int x = 0; x < _items.Count; x++){
   _items.Remove(_items.Where(n => n == _items[x]).Single());
   //You may have to do a notify property changed on this if the UI Doesnt update but thats easily googled.
   //Traditionally it would update. However since you are bound to items Im not sure if it will update when you manipulate _items
}

答案 2 :(得分:0)

创建第二个列表。您仍然必须迭代两次,但第二次迭代不在整个项目列表上。

var items List<ListBoxItem>;
foreach (var item in listbox1.SelectedItems)
    items.Add(item);

foreach (var item in items)
    listbox1.Remove(item);

答案 3 :(得分:0)

或者,不是枚举两次,而是可以创建对象列表的副本,然后在枚举时从原始列表中删除项目。

        foreach (var selectedItem in listBox1.SelectedItems.Cast<List>())
        {
            //remove items from the original list here
        }
相关问题