Search code examples
c#wpfxamlrouted-events

What's wrong with declaration of this routed event?


I've created the following 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);
    }

    ...
}

Now, when I try to use this routed event inside my xaml code:

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

I'm getting following error at compilation:

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

Why am I getting this, and how do I make the routed events work?


Solution

  • Looking at this MSDN Link. It talks about registering a handler which you have done, then it talks about providing the CLR Accessors for the event which I don't see in your code. Then it adds the Event handler. You do not have an Event declaration

    i.e. something like this

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