如何正确处理带有 MessageBox 确认的 PreviewMouseDown 事件?
早些时候我问过如何取消 WPF TreeViewItem.Selected 事件。
回答者建议我在选择发生之前处理 PreviewMouseDown 事件。 这就说得通了。
我尝试这样做...
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
这只是一种工作...
- 如果没有未保存的更改,那么它会正常进行并执行 TreeViewThings_Selected()。
如果有未保存的更改,那么我会看到 MessageBox...
MessageBox:继续并放弃您的未保存的更改? 确定/取消 http://img25.imageshack.us/img25/141/discard2yk0.gif
如果我随后选择“取消”,则会取消。
但是,如果我选择“确定”放弃未保存的更改,那么它无论如何都会取消——即使 e.Handled = False。 它不会继续并执行 TreeViewThings_Selected()。
我认为有一个 MessageBox 的事实不知何故搞砸了。
我究竟做错了什么?
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...
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(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?