我想一些處理程序附加到每個TreeViewItem
,因爲他們被加載,然後刪除處理,因爲它們卸載。Wpf-如何獲取觸發TreeViewItem.Loaded事件的TreeViewItem?
下面是我在從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));
}
編輯:
我仍然無法弄清楚到底是怎麼回事。它只是似乎是不用拿起TreeViewItem
加載事件的TreeView
加載事件。
我已經試過了。出於某種原因,OriginalSource始終是TreeView而不是TreeViewItem。 – Justin 2010-08-30 23:51:05