I am trying to attach some handlers to each TreeViewItem
as they are loaded and then remove the handlers as they are unloaded.
Here is the Code that I have in my custom control which inherits from TreeView
:
public ModdedTreeView()
{
this.AddHandler(TreeViewItem.LoadedEvent, new RoutedEventHandler(ItemLoaded));
this.AddHandler(TreeViewItem.UnloadedEvent, new RoutedEventHandler(ItemUnloaded));
}
protected void ItemLoaded(object sender, RoutedEventArgs e)
{
TreeViewItem item = e.OriginalSource as TreeViewItem;
if (item == null)
return;
item.AddHandler(TreeViewItem.CollapsedEvent, new RoutedEventHandler(ItemCollapsed));
item.AddHandler(TreeViewItem.ExpandedEvent, new RoutedEventHandler(ItemExpanded));
item.AddHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(ItemSelected));
}
protected void ItemUnloaded(object sender, RoutedEventArgs e)
{
TreeViewItem item = e.OriginalSource as TreeViewItem;
if (item == null)
return;
item.RemoveHandler(TreeViewItem.CollapsedEvent, new RoutedEventHandler(ItemCollapsed));
item.RemoveHandler(TreeViewItem.ExpandedEvent, new RoutedEventHandler(ItemExpanded));
item.RemoveHandler(TreeViewItem.SelectedEvent, new RoutedEventHandler(ItemSelected));
}
Edit:
I still can not figure out what is going on. It just seems to be picking up the TreeView
loaded event instead of the TreeViewItem
loaded event.