简体   繁体   English

自定义附加事件的处理程序

[英]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 这里是XAML代码

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

I have this error in runtime at InitializeComponent 我在InitializeComponent运行时遇到此错误

Object of type 'System.String' cannot be converted to type 'System.Windows.RoutedEventHandler'. “System.String”类型的对象无法转换为“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 DropEventArgs代码

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). 几个小时后检查样本和我的代码,问题是因为事件的事件定义确实。(感谢Mihir和Dabblernl)。

I've done a mistake in the 3rd argument of RegisterRoutedEvent method by providing the event type instead of a Handler type. 我通过提供事件类型而不是Handler类型在RegisterRoutedEvent方法的第3个参数中犯了一个错误。

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. 错误消息具有误导性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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