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?
Best Answer
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?