题
我使用附加事件的自定义,我创造,我想一个处理程序添加到该事件
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void dataGridTasks_Drop(object sender, RoutedEventArgs e)
{
}
}
下面的XAML代码
<ListView util:DragDropHelper.Drop="dataGridTasks_Drop">
我在运行时此错误在的InitializeComponent
型的对象“System.String”不能 转换为类型 'System.Windows.RoutedEventHandler'。
任何人都知道为什么我收到此错误? 谢谢!
下面我的事件代码
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代码
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;
}
}
解决方案
几个小时检查样品和我的代码后,该问题是因为确实是事件的事件定义的。(感谢米希尔和Dabblernl)。
我已经通过提供事件类型,而不是一个Handler类型完成在RegisterRoutedEvent方法的第三个参数是错误的。
正确的代码如下:
public delegate void DropEventHandler(object sender, DropEventArgs e);
public static readonly RoutedEvent DropEvent = EventManager.RegisterRoutedEvent(
"Drop", RoutingStrategy.Bubble, typeof(DropEventHandler), typeof(DragDropHelper));
在错误消息被误导。
不隶属于 StackOverflow