WPF: How to created a routed event for content changed?

☆樱花仙子☆ 提交于 2019-12-08 19:01:31

In order to use events with EventTriggers they should be routed events. Routed events are defined in a way similar to dependency properties. Here's a quick tutorial on how to get started: How to: Create a Custom Routed Event.

Here's an example of a class deriving from ContentControl which defines a ContentChanged event:

public class MyContentControl : ContentControl
{
    public static readonly RoutedEvent ContentChangedEvent 
        = EventManager.RegisterRoutedEvent(
            "ContentChanged",
            RoutingStrategy.Bubble,
            typeof(RoutedEventHandler), 
            typeof(MyContentControl));

    public event RoutedEventHandler ContentChanged
    {
        add { AddHandler(ContentChangedEvent, value); }
        remove { RemoveHandler(ContentChangedEvent, value); }
    }

    protected override void OnContentChanged(object oldContent, object newContent)
    {
        base.OnContentChanged(oldContent, newContent);
        RaiseEvent(new RoutedEventArgs(ContentChangedEvent, this));
    }
}

I'm not yet sure why, but while testing this line worked inside a Style, but threw an exception while used in the control's triggers collection directly:

<EventTrigger RoutedEvent="ContentChanged">...</EventTrigger>

In order to make it work in this situation I had to specify a fully qualified event path:

<EventTrigger RoutedEvent="local:MyContentControl.ContentChanged">...</EventTrigger>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!