views:

30

answers:

2

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.

A: 

Loaded is a routed event, so you will find its source in the OriginalSource property, which should be the treeviewitem that triggered the event.

Alex Paven
I've tried that. For some reason OriginalSource is always the TreeView not a TreeViewItem.
Justin
A: 

Apparently the TreeViewItem.Loaded event is a direct event. So there is no way to accomplish what I was trying.

Justin