I've got a WPF application with a Treeview control.
When the user clicks a node on the tree, other TextBox, ComboBox, etc. controls on the page are populated with appropriate values.
The user can then make changes to those values and save his or her changes by clicking a Save button.
However, if the user selects a different Treeview node without saving his or her changes, I want to display a warning and an opportunity to cancel that selection.
XAML…
<TreeView Name="TreeViewThings"
...
TreeViewItem.Unselected="TreeViewThings_Unselected"
TreeViewItem.Selected="TreeViewThings_Selected" >
Visual Basic…
Sub TreeViewThings_Unselected(ByVal sender As System.Object, _ ByVal e As System.Windows.RoutedEventArgs) Dim OldThing As Thing = DirectCast(e.OriginalSource.DataContext, Thing) If CancelDueToUnsavedChanges(OldThing) Then 'put canceling code here End If End Sub Sub TreeViewThings_Selected(ByVal sender As System.Object, _ ByVal e As System.Windows.RoutedEventArgs) Dim NewThing As Thing = DirectCast(e.OriginalSource.DataContext, Thing) PopulateControlsFromThing(NewThing) End Sub
How can I cancel those unselect/select events?
Update: I've asked a follow-up question…
How do I properly handle a PreviewMouseDown event with a MessageBox confirmation?
Best Answer
UPDATE
Realized I could put the logic in SelectedItemChanged instead. A little cleaner solution.
Xaml
Code behind. I have some classes that is my ItemsSource of the TreeView so I made an interface (MyInterface) that exposes the IsSelected property for all of them.
I haven't found any situation where it doesn't revert back to the previous item upon pressing "No".