Remove an item from a list box causes a Catastroph

2019-07-20 21:46发布

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.

3条回答
闹够了就滚
2楼-- · 2019-07-20 22:28

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楼-- · 2019-07-20 22:34

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.

查看更多
做自己的国王
4楼-- · 2019-07-20 22:48

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)

查看更多
登录 后发表回答