vb.net拖放交换标签位置

时间:2015-05-16 21:32:20

标签: vb.net

以下代码应允许用户将一个标签拖到另一个标签上,从而导致两个标签的位置交换。

Dim firstLabel As Label

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Label2.AllowDrop = True
End Sub

Private Sub label1_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles Label1.MouseMove
    If e.Button = MouseButtons.Left Then
        Label1.DoDragDrop(Label1, DragDropEffects.All)
    End If
End Sub

Private Sub label2_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs) Handles Label2.DragEnter
    firstLabel = Label2
    If e.Data.GetDataPresent(GetType(Label)) Then
        e.Effect = DragDropEffects.Copy
    Else
        e.Effect = DragDropEffects.None
    End If
End Sub

Private Sub label2_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs) Handles Label2.DragDrop
    If e.Data.GetDataPresent(GetType(Label)) Then
        Label2 = CType(sender, Label)
        Label1 = firstLabel
    End If
End Sub

我遇到的问题是当我将label1拖放到label2时没有任何反应。 这个问题导致的另一个问题是我需要拖放功能来处理两个以上的标签,我不知道如何有效地制作它。  任何帮助表示赞赏。感谢

1 个答案:

答案 0 :(得分:1)

你大部分都是对的。在DragDrop事件中,您没有使用Label中存储的e.Data和直接引用(即Label1)阻止它以任何方式工作(即L1到L2和L2到L1)。

Private Sub lbl_MouseMove(sender As Object, 
      e As MouseEventArgs) Handles Label1.MouseMove, Label2.MouseMove

    If e.Button = Windows.Forms.MouseButtons.Left Then
        Dim lbl As Label = CType(sender, Label)
        ' sender could be Lbl1 or Lbl2 - we dont care
        lbl.DoDragDrop(lbl, DragDropEffects.Move)
    End If

End Sub

由于sender是被拖动的,因此将其强制转换为标签,并将其设置为拖动数据对象。另请注意,如何通过Handles子句设置一个事件来处理两个标签。这也适用于DragEnter:

Private Sub Lbl_DragEnter(sender As Object, 
      e As DragEventArgs) Handles Label1.DragEnter, Label2.DragEnter

然后,在DragDrop事件中,只需交换2个标签中的Location

' handles DragDrop for both controls (or more)
Private Sub Lbl_DragDrop(sender As Object, 
        e As DragEventArgs) Handles Label1.DragDrop, Label2.DragDrop

    If e.Data.GetDataPresent(GetType(Label)) = False Then Exit Sub

    ' sender == Droppee
    Dim lblA As Label = CType(sender, Label)
    ' e.Data == Dragee
    Dim lblB As Label = CType(e.Data.GetData(GetType(Label)), Label)

    Dim pt As Point = lblA.Location

    ' swap locations
    lblA.Location = lblB.Location
    lblB.Location = pt

End Sub

sender是一个标签,e.Data是另一个标签。我们不需要知道哪个是重要的,我们想要交换位置。