I have two TreeViews
in my program that deal with SelectedItemChanged
in the same way. The problem is that one works fine and the other one throws a NullReferenceException
. The exception gets thrown in one of the trees when a node is deselected...
How SelectedItemChanged
is handled for both trees in the code-behind:
//How *ViewModel* is declared...
public DatabaseViewModel ViewModel { get { return DataContext as DatabaseViewModel; } }
//Gets selected item in TreeView
private void Tree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
var data = e.NewValue as TreeModel;
ViewModel.Tree.SelectedItem = data;
}
This is basically what happens:
-A node in the problem tree is selected
-Next, a node in the well-behaved tree is selected
-A NullReferenceException
is then thrown on the line: ViewModel.Tree.SelectedItem = data.
in the problem tree's code-behind. The exception says: "Object reference not set to an instance of an object".
What is going wrong here and how can I fix it? Thank you.
*Note: I'd just like to point out that this does not happen for the other tree.
Try this :
//Gets selected item in TreeView
private void Tree_SelectedItemChanged(object sender,RoutedPropertyChangedEventArgs<object> e)
{
var data = e.NewValue as TreeModel;
if(data!=null)
ViewModel.Tree.SelectedItem = data;
}