Remove an item from a list box causes a Catastrophic Failure?

你。 提交于 2019-12-11 00:30:28

问题


I am trying to clear a list box's items in my Windows RT App. To add the items, I use:

List<string> list1;
...
foreach(string s in list1.Items)
{
    listBox1.Items.Add(s);
}

To clear the items, I use:

listBox1.Items.Clear();

However, this throws this exception:

Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))

If I try to use:

        int at = 0;
        while (at < listBox1.Items.Count)
        {
            listBox1.Items.RemoveAt(at);
            at += 1;
        }

I get the same exception at the RemoveAt method.


回答1:


I found the solution to this problem. I was trying to remove items from a method fired by the SelectionChanged event. I changed this to:

await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, listBox1.Items.Clear);

And it works fine.




回答2:


For the second one, you really don't want to increment 'at'

If you delete the item at 0 - the item at 1 will become the item at 0 now.

so

while (listBox1.Items.Count != 0)
{
listBox1.Items.RemoveAt(0);

}

will work.

Not sure why you're getting an exception in the first one - did you initiate the listbox somewhere?




回答3:


If your list is bound to some data using DataBinding, then work on the data model behind and not on the ListItems.

(The list will get updated if you have properly implemented INotifyPropertyChanged interface)



来源:https://stackoverflow.com/questions/13103575/remove-an-item-from-a-list-box-causes-a-catastrophic-failure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!