阻止用户取消选择ListBox中的项目?

mpe*_*pen 8 c# wpf xaml

我有一个包含大量项目的ListBox.用户可以单击项目以编辑其内容.如何阻止用户取消选择所有项目?即,用户不应该没有选择任何东西.

Joã*_*ela 6

您的情况缺少一种情况,即当列表被清除时,您将重新选择列表中不再存在的项目。我通过添加额外的检查来解决这个问题。

        var listbox = ((ListBox)sender);
        if (listbox.SelectedItem == null)
        {
            if (e.RemovedItems.Count > 0)
            {
                object itemToReselect = e.RemovedItems[0];
                if (listbox.Items.Contains(itemToReselect))
                {
                    listbox.SelectedItem = itemToReselect;
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

然后我把它放在一个行为中