我有一个WPF 4 / VB.net 2010项目,我正在尝试进行视觉“拖放”(在MouseUp上有一个对象跟随鼠标,在MouseDown上有“粘贴”。)我有以下内容代码背后:
Private Sub Tile1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Tile1.MouseDown
Tile1.CaptureMouse()
IsDragging = True
End Sub
Private Sub Tile1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles Tile1.MouseMove
If IsDragging = True Then
Dim canvPosToWindow As Point = canv.TransformToAncestor(Me).Transform(New Point(0, 0))
Dim r As Rectangle = TryCast(sender, Rectangle)
Dim upperlimit As Double = canvPosToWindow.Y + (r.Height / 2)
Dim lowerlimit As Double = canvPosToWindow.Y + canv.ActualHeight - (r.Height / 2)
Dim leftlimit As Double = canvPosToWindow.X + (r.Width / 2)
Dim rightlimit As Double = canvPosToWindow.X + canv.ActualWidth - (r.Width / 2)
Dim absmouseXpos As Double = e.GetPosition(Me).X
Dim absmouseYpos As Double = e.GetPosition(Me).Y
If (absmouseXpos > leftlimit AndAlso absmouseXpos < rightlimit) AndAlso (absmouseYpos > upperlimit AndAlso absmouseYpos < lowerlimit) Then
r.SetValue(Canvas.LeftProperty, e.GetPosition(canv).X - (r.Width / 2))
r.SetValue(Canvas.TopProperty, e.GetPosition(canv).Y - (r.Height / 2))
End If
End If
End Sub
Private Sub Tile1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Tile1.MouseUp
Tile1.ReleaseMouseCapture()
IsDragging = False
End Sub
我收到此错误:
NullReferenceException,对象引用未设置为对象的实例。
在以下每一行中:
Dim upperlimit As Double = canvPosToWindow.Y + (r.Height / 2)
Dim lowerlimit As Double = canvPosToWindow.Y + canv.ActualHeight - (r.Height / 2)
Dim leftlimit As Double = canvPosToWindow.X + (r.Width / 2)
Dim rightlimit As Double = canvPosToWindow.X + canv.ActualWidth - (r.Width / 2)
我做错了什么?
答案 0 :(得分:1)
我怀疑这句话使得r“null”而不是一个合适的矩形。
Dim r As Rectangle = TryCast(sender, Rectangle)
发件人可能不是一个矩形,但可能是一个WPF-Control(System.Windows.Controls.Control的某个子类)。
您可以使用Visual Studio调试器轻松检查,在此行上放置一个调试点,并查看此语句是否已评估。
祝你拖放实现好运:)。