2012-05-15 24 views
0

我創建了以下用戶控件:聲明此路由事件有什麼問題?

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' 

爲什麼我得到這個,以及如何使路由事件工作?

回答

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