2013-06-19 44 views
1

我需要你来帮助解决我的问题。当我在我的代码中使用listbox ItemSource时,所选项目不能被删除。不使用ListBox ItemsSource,删除操作正在工作。为什么?请给我你的灵魂代码。我需要为列表框添加ItemsSource。非常感谢!哦,是的,我正在使用C#4.5和WPF。listbox selecteditems无法删除由于使用ItemsSource

public SendEmail(List<string> items, ItemCollection needsItems) 
    : this() 
    { 
     _needList = needsItems; 

     lstNeeds.ItemsSource = _needList; 
    } 

    //Remove selected Items not working 

if (lstNeeds.SelectedItem != null) 
    { 

     for (int i = lstNeeds.SelectedItems.Count - 1; i >= 0; i--) 
     { 
     lstNeeds.Items.Remove(lstNeeds.SelectedItems[i]); 
     } 
    } 

enter image description here

+0

@PoweredByOrange是“黑暗”的主题,我认为,以设置去工具 - >选项 - >环境 - >常规的右侧有列表(颜色主题组合框)的主题选择“黑暗”一个 – Jamaxack

回答

2

你想从你遍历集合中删除的项。

+0

它现在工作,谢谢你的建议 – user1358072

0

试试这个:

if (lstNeeds.SelectedItem != null) 
{ 
    List<Int32> selIdx = new List<Int32>(); 
    foreach (var item in lstNeeds.SelectedItems) 
     selIdx.Add(lstNeeds.Items.IndexOf(item); 
    selIdx.Sort(); //necessary? 
    for (Int32 idx = selIdx.Count - 1; i >= 0; i--) 
    { 
     lstNeeds.Items.RemoveAt(selIdx[i]); 
    } 
} 
+0

SelectedIndices不存在于智能感知中。 – user1358072

+0

我看到你是正确的(我不使用WPF,抱歉)。编辑。 – DonBoitnott

+0

感谢您的编辑,但您的代码不工作,因为我收到错误消息:在ItemsSource正在使用时,操作无效。改为使用ItemsControl.ItemsSource访问和修改元素。 – user1358072