潜移默化学会WPF--拖放 学习(一)
/// <summary> /// Window1.xaml 的交互逻辑 /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); this.rectangle1.PreviewMouseMove += new MouseEventHandler(rectangle1_PreviewMouseMove); this.canvas2.DragOver += new DragEventHandler(canvas2_DragOver); this.canvas2.Drop += new DragEventHandler(canvas2_Drop); } void canvas2_Drop(object sender, DragEventArgs e) { IDataObject data = e.Data; if (data.GetDataPresent(typeof(Rectangle))) { Rectangle rect = data.GetData(typeof(Rectangle)) as Rectangle; this.canvas1.Children.Remove(rect); this.canvas2.Children.Add(rect); } } void canvas2_DragOver(object sender, DragEventArgs e) { if (!e.Data.GetDataPresent(typeof(Rectangle))) { e.Effects = DragDropEffects.None; e.Handled = true; } } void rectangle1_PreviewMouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { DataObject data = new DataObject(typeof(Rectangle), this.rectangle1); DragDrop.DoDragDrop(this.rectangle1, data, DragDropEffects.Move); } }
前台
<Window x:Class="DragDropDemo1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="319" Width="494"> <Grid> <Canvas Margin="14,19,216,20" Name="canvas1" Background="Azure"> <Rectangle Height="53" Name="rectangle1" Stroke="Black" Width="91" Fill="Crimson" /> </Canvas> <Canvas HorizontalAlignment="Right" Margin="0,22,5,21" Name="canvas2" Width="199" Background="DarkSalmon" AllowDrop="True" /> </Grid> </Window>
本例子来于网上 http://msdn.microsoft.com/zh-cn/ff685657.aspx 本文来自.NET开发者 作者:苏扬