声明此路由事件有什么问题?

时间:2012-05-15 21:07:35

标签: c# wpf xaml routed-events

我创建了以下UserControl:

public partial class ReplacementPatternEditor : UserControl, INotifyPropertyChanged
{
    ....

    public static readonly RoutedEvent CollectionChanged = EventManager.RegisterRoutedEvent(
        "CollectionChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ReplacementPatternEditor));

    void RaiseCollectionChangedEvent()
    {
        RoutedEventArgs newEventArgs = new RoutedEventArgs(ReplacementPatternEditor.CollectionChanged);
        RaiseEvent(newEventArgs);
    }

    ...
}

现在,当我尝试在我的xaml代码中使用此路由事件时:

<local:ReplacementPatternEditor ItemsSource="{Binding MyItemSource}" CollectionChanged="OnCollectionChanged"/>

我在编译时遇到以下错误:

The property 'CollectionChanged' does not exist in XML namespace 'clr-namespace:MyNamespace'

为什么我会这样做,以及如何使路由事件发挥作用?

1 个答案:

答案 0 :(得分:2)

看看这个MSDN Link。它讨论了注册你已经完成的处理程序,然后讨论为我在代码中看不到的事件提供CLR访问器。然后它添加了事件处理程序。您没有活动声明

即。像这样的东西

public static readonly RoutedEvent CollectionChangedEvent = EventManager.RegisterRoutedEvent( 
    "CollectionChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ReplacementPatternEditor)); 

public event RoutedEventHandler CollectionChanged
{
    add { AddHandler(CollectionChangedEvent, value); } 
    remove { RemoveHandler(CollectionChangedEvent, value); }
}


void RaiseCollectionChangedEvent() 
{ 
    RoutedEventArgs newEventArgs = new RoutedEventArgs(ReplacementPatternEditor.CollectionChanged); 
    RaiseEvent(newEventArgs); 
}