2
votes

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
Have you stepped through your preview mouse down handler in the debugger to see if it is working as you expected? You should be able to see if e.Handled is being set to true/false and when. If it is, you know there is a problem with the box.Josh G
I have stepped through with the debugger. e.Handled is getting set as expected. I don't know why, but the MessageBox itself seems to be the problem.Zack Peterson
I've asked a follow-up question: stackoverflow.com/questions/546388/…Zack Peterson

1 Answers

1
votes

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?