如何在 UWP 中清除虚拟化 ListView 上的选择?

Gee*_*rik 4 listview win-universal-app

我很怀疑。我有一个大列表容器,可能有数千个项目。当我虚拟化(这几乎是对性能的需求)时,一旦我尝试更新选择,我就会收到此异常:

Failed to update selection | [Exception] System.Exception: Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))
   at System.Runtime.InteropServices.WindowsRuntime.IVector`1.RemoveAt(UInt32 index)
   at System.Runtime.InteropServices.WindowsRuntime.VectorToListAdapter.RemoveAtHelper[T](IVector`1 _this, UInt32 index)
   at System.Runtime.InteropServices.WindowsRuntime.VectorToListAdapter.RemoveAt[T](Int32 index)
   at MyApp.Views.SearchView.<>c__DisplayClass9_0.<UpdateListViewSelection>b__0()
   at MyApp.Views.SearchView.<>c__DisplayClass10_0.<<ExecuteSafely>b__0>d.MoveNext()
Run Code Online (Sandbox Code Playgroud)

我尝试通过两种方式清除选择:

A:

listView.SelectedItems.Clear();
Run Code Online (Sandbox Code Playgroud)

乙:

for (int i = 0; i < listView.SelectedItems.Count; i++)
{
    listView.SelectedItems.RemoveAt(i--);
}
Run Code Online (Sandbox Code Playgroud)

另一种选择是不虚拟化,但更糟糕的是......任何人都知道如何安全地清除 UWP 中虚拟化列表视图上的选择?

Gee*_*rik 5

基于SelectionModeListView的正确方法清除似乎很重要。下面是一种清除 ListView 选择的安全方法(无需关心SelectionMode自己):

public static void ClearSelection(this ListViewBase listView)
{
    Argument.IsNotNull(() => listView);

    switch (listView.SelectionMode)
    {
        case ListViewSelectionMode.None:
            break;

        case ListViewSelectionMode.Single:
            listView.SelectedItem = null;
            break;

        case ListViewSelectionMode.Multiple:
        case ListViewSelectionMode.Extended:
            listView.SelectedItems.Clear();
            break;

        default:
            throw new ArgumentOutOfRangeException();
    }
}
Run Code Online (Sandbox Code Playgroud)