<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.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfApplication1
{
public partial class Window1 : Window
{
private ListBoxItem draggedItem;
private Point startDragPoint;
public Window1()
{
InitializeComponent();
}
private void cvsSurface_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effects = DragDropEffects.Copy;
}
else
{
e.Effects = DragDropEffects.None;
}
}
private void cvsSurface_Drop(object sender, DragEventArgs e)
{
Label newLabel = new Label();
newLabel.Content = e.Data.GetData(DataFormats.Text);
cvsSurface.Children.Add(newLabel);
Canvas.SetLeft(newLabel,100);
Canvas.SetTop(newLabel, 200);
}
private void ListBoxItem_PreviewMouseLeftButtonDown(object sender,MouseButtonEventArgs e)
{
draggedItem = sender as ListBoxItem;
startDragPoint = e.GetPosition(null);
}
private void ListBoxItem_PreviewMouseMove(object sender,MouseEventArgs e)
{
Point position = e.GetPosition(null);
DragDrop.DoDragDrop(draggedItem, draggedItem.Content,DragDropEffects.Copy);
}
}
}
|