How do I properly handle a PreviewMouseDown event with a MessageBox confirmation?

独自空忆成欢 提交于 2019-12-20 03:47:12

问题


Earlier I asked how to cancel a WPF TreeViewItem.Selected event.

The answerers suggested I instead handle the PreviewMouseDown event before the selection even takes place. That makes sense.

I've tried to do that...

XAML...

<TreeView Name="TreeViewThings"
    ...
    PreviewMouseDown="TreeViewThings_PreviewMouseDown"
    TreeViewItem.Expanded="TreeViewThings_Expanded"
    TreeViewItem.Selected="TreeViewThings_Selected" >

Visual Basic...

Sub TreeViewThings_PreviewMouseDown(...)
    If UnsavedChangesExist() Then
        e.Handled = UserCancelled()
    Else
        e.Handled = False
    End If
End Sub

Function UnsavedChangesExist() As Boolean
    ...
End Function

Function UserCancelled() As Boolean
    Return MessageBox.Show("Discard your unsaved changes?", _
                           "Unsaved Changes", _
                           MessageBoxButton.OKCancel, _
                           MessageBoxImage.Question) = MessageBoxResult.Cancel
End Function

This is only sort of working...

  • If there are no unsaved changes, then it proceeds just fine and executes TreeViewThings_Selected().

If there are unsaved changes, then I see the MessageBox...

MessageBox: Continue and discard your unsaved changes? OK/Cancel http://img25.imageshack.us/img25/141/discard2yk0.gif

  • If I then choose Cancel, it cancels.

  • However, If I instead choose OK to discard my unsaved changes, then it just cancels anyway--even though e.Handled = False. It does not continue on and execute TreeViewThings_Selected().

I think the fact that there's a MessageBox screws it up somehow.

What am I doing wrong?


回答1:


The problem is that the messagebox causes your tree to lose focus. Have you tried setting the focus back to the tree after the messagebox is dismissed?



来源:https://stackoverflow.com/questions/543312/how-do-i-properly-handle-a-previewmousedown-event-with-a-messagebox-confirmation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!