开发者

Simulated Visual Drag/Drop (What is Wrong w/ This Code?)

I have a WPF 4/VB.net 2010 project, and I'm trying to do a visual "drag and drop" (having an object follow the mouse on MouseUp and "stick" on MouseDown.) I have the following code behind:

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

I am getting this error:

NullReferenceException, Object reference not set to an instance of an object.

On each of the following lines:

 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)

What am I doing wrong?


I suspect that this statement makes r "null" and not a proper rectangle.

Dim r As Rectangle = TryCast(sender, Rectangle)

The sender is probably not a rectangle but probably a WPF-Control (some subclass of System.Windows.Controls.Control).

You can easily check with the Visual Studio debugger, by placing a debug-point on this line and see if this statement evaluates.

Good luck with your drag-drop implementation :).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜