Drag Items from a List and Drop Them on a Canvas
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF " Height="300" Width="300">
<DockPanel LastChildFill="True" >
<ListBox DockPanel.Dock="Left" Name="lstLabels">
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListBoxItem_PreviewMouseLeftButtonDown"/>
<EventSetter Event="PreviewMouseMove" Handler="ListBoxItem_PreviewMouseMove"/>
</Style>
</ListBox.Resources>
<ListBoxItem>A</ListBoxItem>
<ListBoxItem>B</ListBoxItem>
<ListBoxItem>C</ListBoxItem>
<ListBoxItem>D</ListBoxItem>
<ListBoxItem>E</ListBoxItem>
<ListBoxItem>F</ListBoxItem>
<ListBoxItem>G</ListBoxItem>
<ListBoxItem>H</ListBoxItem>
</ListBox>
<Canvas AllowDrop="True" Background="Red"
DragEnter="cvsSurface_DragEnter" Drop="cvsSurface_Drop"
Name="cvsSurface" >
</Canvas>
</DockPanel>
</Window>
//File:Window.xaml.vb
Imports System
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Input
Namespace WpfApplication1
Public Partial Class Window1
Inherits Window
Private draggedItem As ListBoxItem
Private startDragPoint As Point
Public Sub New()
InitializeComponent()
End Sub
Private Sub cvsSurface_DragEnter(sender As Object, e As DragEventArgs)
If e.Data.GetDataPresent(DataFormats.Text) Then
e.Effects = DragDropEffects.Copy
Else
e.Effects = DragDropEffects.None
End If
End Sub
Private Sub cvsSurface_Drop(sender As Object, e As DragEventArgs)
Dim newLabel As New Label()
newLabel.Content = e.Data.GetData(DataFormats.Text)
cvsSurface.Children.Add(newLabel)
Canvas.SetLeft(newLabel, 100)
Canvas.SetTop(newLabel, 200)
End Sub
Private Sub ListBoxItem_PreviewMouseLeftButtonDown(sender As Object, e As MouseButtonEventArgs)
draggedItem = TryCast(sender, ListBoxItem)
startDragPoint = e.GetPosition(Nothing)
End Sub
Private Sub ListBoxItem_PreviewMouseMove(sender As Object, e As MouseEventArgs)
Dim position As Point = e.GetPosition(Nothing)
DragDrop.DoDragDrop(draggedItem, draggedItem.Content, DragDropEffects.Copy)
End Sub
End Class
End Namespace
Related examples in the same category