简体   繁体   中英

Handler for Custom Attached Event

I'm using a custom Attached Event that I created and I'm trying to add a handler to this event

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void dataGridTasks_Drop(object sender, RoutedEventArgs e)
    {

    }
}

Here the XAML code

<ListView  util:DragDropHelper.Drop="dataGridTasks_Drop">

I have this error in runtime at InitializeComponent

Object of type 'System.String' cannot be converted to type 'System.Windows.RoutedEventHandler'.

Anyone knows why i'm getting this error ? Thanks !

Here my Event code

    public static readonly RoutedEvent DropEvent = EventManager.RegisterRoutedEvent(
        "Drop", RoutingStrategy.Bubble, typeof(DropEventArgs), typeof(DragDropHelper));

    public static void AddDropHandler(DependencyObject d, RoutedEventHandler handler)
    {
        UIElement uie = d as UIElement;
        if (uie != null)
        {
            uie.AddHandler(DragDropHelper.DropEvent, handler);
        }
    }

    public static void RemoveDropHandler(DependencyObject d, RoutedEventHandler handler)
    {
        UIElement uie = d as UIElement;
        if (uie != null)
        {
            uie.RemoveHandler(DragDropHelper.DropEvent, handler);
        }
    }

DropEventArgs code

class DropEventArgs : RoutedEventArgs
{
    public object Data { get; private set; }
    public int Index { get; private set; }

    public DropEventArgs(RoutedEvent routedEvent, object data, int index) 
        : base(routedEvent)
    {
        Data = data;
        Index = index;
    }
}

After few hours checking the samples and my code, the problem was because of event definition of the Event indeed.(Thanks Mihir and Dabblernl).

I've done a mistake in the 3rd argument of RegisterRoutedEvent method by providing the event type instead of a Handler type.

The correct code is the following :

    public delegate void DropEventHandler(object sender, DropEventArgs e);

    public static readonly RoutedEvent DropEvent = EventManager.RegisterRoutedEvent(
        "Drop", RoutingStrategy.Bubble, typeof(DropEventHandler), typeof(DragDropHelper));

The error message was misleading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM