如何使用MessageBox确认正确地处理PreviewMouseDown事件?

时间:2022-02-13 00:01:24

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

之前我问过如何取消WPF TreeViewItem。选择事件。

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

回答者建议我在选择之前处理PreviewMouseDown事件。这是有意义的。

I've tried to do that...

我试过这么做……

XAML...

XAML……

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

Visual Basic...

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().
  • 如果没有未保存的更改,则执行TreeViewThings_Selected()。

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

如果有未保存的更改,那么我将看到MessageBox…

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

MessageBox:继续并丢弃您未保存的更改?好的/取消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().

    但是,如果我选择OK来丢弃未保存的更改,那么它就会被取消——即使是e。= False来处理。它不会继续并执行TreeViewThings_Selected()。

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

我认为有一个消息框把它搞砸了。

What am I doing wrong?

我做错了什么?

1 个解决方案

#1


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?

问题是,messagebox导致您的树失去焦点。您是否尝试过在取消消息框后将焦点重新设置到树中?

#1


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?

问题是,messagebox导致您的树失去焦点。您是否尝试过在取消消息框后将焦点重新设置到树中?