问题描述
之前我问过如何取消 WPF TreeViewItem.Selected事件.
回答者建议我在选择发生之前处理 PreviewMouseDown 事件.这是有道理的.
我已经尝试这样做了...
XAML...
Visual Basic...
子 TreeViewThings_PreviewMouseDown(...)如果 UnsavedChangesExist() 那么e.Handled = UserCancelled()别的e.处理=假万一结束子函数 UnsavedChangesExist() 作为布尔值...结束函数函数 UserCancelled() 作为布尔值Return MessageBox.Show("放弃你未保存的更改?", _未保存的更改", _MessageBoxButton.OKCancel, _MessageBoxImage.Question) = MessageBoxResult.Cancel结束函数这只是一种工作......
- 如果没有未保存的更改,那么它会继续执行并执行 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?
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 确认正确处理 PreviewMouseDown 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!