Remove an item from a list box causes a Catastroph

2019-07-20 22:34发布

问题:

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)