tags:

views:

23

answers:

2

To handle the TreeView.SelectedItemChanged event, I have an attached behavior that binds to a command.

Ordinarily, the RoutedPropertyChangedEventArgs.NewValue property contains a reference to one of my view-model objects, and I can then pass this on as the argument to ICommand.CanExecute and ICommand.Execute. I'm using RelayCommand from here, but I've got a RelayCommand<T> that casts to the expected type.

However, in certain scenarios, RoutedPropertyChangedEventArgs.NewValue contains a TreeViewItem, displayed as {System.Windows.Controls.TreeViewItem Header:{DisconnectedItem} Items.Count:0} in the debugger.

This causes my RelayCommand<T> to throw an InvalidCastException.

Question: what is this mysterious TreeViewItem and where does it come from?

I'm aware that I can avoid the exception by changing RelayCommand<T>.Execute from using (T)value to using value as T, but I'd like to know what the root cause is.

A: 

A DisconnectedItem is a TreeViewItem that is no longer in your TreeView (i.e. that has been removed from the tree).

bitbonk
OK. Any idea why I'm seeing one in the SelectionChanged event handler?
Roger Lipscombe
A: 

Interesting; do you do anything out of the ordinary with the treeview, as in control templating? Is it the actual built-in treeview or a class that inherits it? It could have something to do with virtualization but it definitely shouldn't happen ordinarily I think.

Alex Paven
I have an `<ItemTemplate>` and an `<ItemContainerStyle>`, but I've not done anything (yet) with control templating.
Roger Lipscombe