我想在WPF中使用TreeView.AfterCollapse事件。 有没有办法使用它? 为什么WPF不支持所有事件? 谢谢
答案 0 :(得分:6)
TreeViewItem
有一个Collapsed
事件,相当于Windows窗体中的AfterCollapsed
事件。此事件最初是由TreeViewItem
而不是TreeView
引发的,但由于这是一个冒泡事件,因此它也会在TreeView
之后被提升,因此您可以在此级别处理它你需要。您可以使用OriginalSource
属性来获取引发事件的TreeViewItem
:
<强> XAML 强>
<TreeView TreeViewItem.Collapsed="TreeViewItem_Collapsed" ...>
<强>代码隐藏强>
private void TreeViewItem_Collapsed(object sender, RoutedEventArgs e)
{
TreeViewItem tvi = (TreeViewItem)e.OriginalSource;
...
}
答案 1 :(得分:0)
您可以扩展TreeViewItem对象以添加此功能。
以下是我使用过的一个例子。它来自Wei Zhou,其MSDN帖子为我节省了几次:
public class MyTreeViewItem : TreeViewItem
{
public static readonly RoutedEvent CollapsingEvent =
EventManager.RegisterRoutedEvent("Collapsing",
RoutingStrategy.Bubble, typeof(RoutedEventHandler),
typeof(MyTreeViewItem));
public static readonly RoutedEvent ExpandingEvent =
EventManager.RegisterRoutedEvent("Expanding",
RoutingStrategy.Bubble, typeof(RoutedEventHandler),
typeof(MyTreeViewItem));
public event RoutedEventHandler Collapsing
{
add { AddHandler(CollapsingEvent, value); }
remove { RemoveHandler(CollapsingEvent, value); }
}
public event RoutedEventHandler Expanding
{
add { AddHandler(ExpandingEvent, value); }
remove { RemoveHandler(ExpandingEvent, value); }
}
protected override void OnExpanded(RoutedEventArgs e)
{
OnExpanding(new RoutedEventArgs(ExpandingEvent, this));
base.OnExpanded(e);
}
protected override void OnCollapsed(RoutedEventArgs e)
{
OnCollapsing(new RoutedEventArgs(CollapsingEvent, this));
base.OnCollapsed(e);
}
protected virtual void OnCollapsing(RoutedEventArgs e) { RaiseEvent(e); }
protected virtual void OnExpanding(RoutedEventArgs e) { RaiseEvent(e); }
}