为什么不在WPF控件中的所有事件

时间:2011-08-19 23:04:15

标签: wpf events

我想在WPF中使用TreeView.AfterCollapse事件。 有没有办法使用它? 为什么WPF不支持所有事件? 谢谢

2 个答案:

答案 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); }
}