Wpf- How can I get the TreeViewItem that triggered the TreeViewItem.Loaded event?
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 se开发者_JAVA技巧nder, 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.
Loaded is a routed event, so you will find its source in the OriginalSource
property, which should be the treeviewitem that triggered the event.
Apparently the TreeViewItem.Loaded event is a direct event. So there is no way to accomplish what I was trying.
精彩评论