0

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.

Eric after dark
  • 1,768
  • 4
  • 31
  • 79
  • Have you verified that the DataContext in the bad case is actually an instance of DatabaseViewModel? Set a breakpoint on the line where the exception is thrown, then you can check the DataContext. – foosburger Nov 01 '13 at 20:37

1 Answers1

1

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;
}
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67