Winforms ListView ItemSelectionChanged激发的频率高于预期

Winforms ListView ItemSelectionChanged激发的频率高于预期,winforms,listview,c++-cli,Winforms,Listview,C++ Cli,这与归结为“取消选择”和“选择”事件的情况不同。我看到的不是每次选择改变两次,而是四次。简化代码: System::Void myclass::handleSelectionChange(Object ^ sender, ListViewItemSelectionChangedEventArgs ^ args) { if(myListView->SelectedIndices->Count == 1) { // This also serves to filter out "

这与归结为“取消选择”和“选择”事件的情况不同。我看到的不是每次选择改变两次,而是四次。简化代码:

System::Void myclass::handleSelectionChange(Object ^ sender, ListViewItemSelectionChangedEventArgs ^ args) {
    if(myListView->SelectedIndices->Count == 1) { // This also serves to filter out "deselect" events (MultiSelect = false)
        if(myUnsavedChanges && myListView->SelectedIndices[0] != myPreviousSelection) { // No need for this bit if the newly-selected item is the "dirty" item
            Windows::Forms::DialogResult response = MessageBox::Show("Save your changes?", "Unsaved changes", MessageBoxButtons::YesNoCancel, MessageBoxIcon::Warning);
            if(response == Windows::Forms::DialogResult::Cancel) {
                // re-select the edited item
                myListView->SelectedIndices->Clear();
                myListView->SelectedIndices->Add(myPreviousSelection);
            } else if(response == Windows::Forms::DialogResult::Yes) {
                // save the changes, don't reselect the edited item
            } else if(response == Windows::Forms::DialogResult::No) {
                // let the changes be lost
            }
        }
    }
}
当我在表单中进行更改后单击某个项目时,我收到了许多调试消息,清楚地显示了以下事件过程:

  • handleSelectionChange
    通过取消选择“脏”项进入(和退出)
  • handleSelectionChange
    通过选择单击的项目进入
  • 出现
    消息框
    ,我单击“取消”
  • handleSelectionChange
    通过取消选择单击的项目进入(和退出)
  • handleSelectionChange
    通过选择“脏”项进入
  • …然后它变得有趣:

  • handleSelectionChange
    再次取消选择“脏”项进入(和退出)
  • handleSelectionChange
    再次进入并选择单击的项目
  • 出现
    消息框
    ,我再次单击“取消”
  • handleSelectionChange
    再次取消选中所单击的项目后进入(和退出)
  • handleSelectionChange
    再次进入并选择“脏”项
  • 然后一切都安定下来,ListView显示先前选择的项目(“脏”项目)

    更奇怪的是,如果我在委托中的任何位置有一个断点,问题就不会发生(只发生事件1-5)

    我甚至尝试过使用BeginInvoke来更改选择,以便在代理退出后进行编程选择更改,但没有效果。行为还是一样的。如果我删除MessageBox并使代码采用“Cancel”路径,那么行为将包括步骤6之前的所有内容,最后我没有选择任何内容。因此,这并不完全是MessageBox的错,尽管这会影响行为

    为什么会这样?为什么事件序列在步骤5之后不停止?其他ItemSelectionChanged事件来自何处