Wpf AddHandler Lambda表达式

Wpf AddHandler Lambda表达式,wpf,vb.net,lambda,expression,Wpf,Vb.net,Lambda,Expression,守则: Dim x, y as [Delegate] x = Sub() MeMouseMove(points) y = Sub() MeMouseDown(points) AddHandler MainGrid.MouseMove, x AddHandler MainGrid.MouseLeftButtonDown, y 代码背景: “主网格”是一个网格,其大小和宽度与其所在的窗口相同 “x”和“y”声明为[委托] “points”是我需要通过编程创

守则:

    Dim x, y as [Delegate]
    x = Sub() MeMouseMove(points)
    y = Sub() MeMouseDown(points)
    AddHandler MainGrid.MouseMove, x
    AddHandler MainGrid.MouseLeftButtonDown, y
代码背景:

  • “主网格”是一个网格,其大小和宽度与其所在的窗口相同
  • “x”和“y”声明为[委托]
  • “points”是我需要通过编程创建的处理程序传递的类
  • “MeMouseMove”和“MeMouseDown”是我需要调用的sub
问题是:

我得到一个错误:

发生“System.InvalidCastException”类型的未处理异常
其他信息:无法将类型为“VB$AnonymousDelegate_0”的对象强制转换为类型为“System.Windows.Input.MouseEventHandler”

我认为问题在于x和y变量的声明


如果您有任何帮助,我们将不胜感激,并感谢您的时间,Red

MouseEventHandler有两个参数Object sender和RoutedEventArgs e,因此您应该尝试一下

x = Sub(s, e) MeMouseMove(points)
y = Sub(s, e) MeMouseDown(points)
AddHandler MainGrid.MouseMove, AddressOf x
AddHandler MainGrid.MouseLeftButtonDown, AddressOf y
找到了解决办法

        Dim x As New MouseEventHandler(Sub() MeMouseMove(points))
        Dim y As New MouseButtonEventHandler(Sub() MeMouseDown(points))

将变量“x”和“y”更改为正确的变量类型(不是[Delegate])

一个MouseEventHandler有两个参数,而你的lamda没有。@HansPassant不起作用(见下面bonyjoe的答案)尝试:将变量类型更改为nothing(例如:“Dim x,y”)。与initialBump相同的问题。如果你需要帮助,那也会出现同样的问题。但是感谢您的回复,现在尝试编辑,我总是忘记您需要VBAddressOf中的AddressOf运算符AddressOf不起作用,因为:“AddressOf”操作数必须是方法的名称(不带括号)。谢谢你的帮助,瑞达好吧,那就最后一次尝试吧。将(s,e)替换为(sender As Object,e As EventArgs),并丢失运算符的地址如果您只是直接在addhandler调用中声明匿名方法,它是否有效?AddHandler MainGrid.MouseMove,子(…)。。。。。。