wpf 实现控件拖拽(仿windows 桌面图标拖拽)
一直觉得拖拖拽控件很有用,但却一直没用它做过东西,今天来实践一下
实现的效果就参考桌面上的图标拖放把
实现效果如下,主要用到 1VisualBrush 来仿制被拖控件的样子, 2DragDrop相关类和函数的使用详情看代码把
<Canvas Name="myGrid" AllowDrop="True" Background="AliceBlue" Drop="myGrid_Drop" PreviewDragOver="myGrid_DragOver"> <Button x:Name="btn" PreviewMouseLeftButtonDown="Button_MouseLeftButtonDown" AllowDrop="True" Height="39.127" Canvas.Left="37.422" Canvas.Top="30.084" Width="61.774"> <Button.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFF7F5F5" Offset="0"/> <GradientStop Color="#FF319744" Offset="1"/> </LinearGradientBrush> </Button.Background> hello </Button> <Rectangle x:Name="rt"></Rectangle> </Canvas>
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } Point point; private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { VisualBrush vb = new VisualBrush(sender as Button); rt.Width = btn.ActualWidth; rt.Height = btn.ActualHeight; rt.Fill = vb; Canvas.SetLeft(rt, Canvas.GetLeft(btn)); Canvas.SetTop(rt, Canvas.GetTop(btn)); point = e.GetPosition(myGrid); rt.Visibility = Visibility.Visible; DragDrop.DoDragDrop(btn, btn, DragDropEffects.Move); } private void myGrid_DragOver(object sender, DragEventArgs e) { var newpoint = e.GetPosition(myGrid); var leftmove = newpoint.X - point.X; var topmove = newpoint.Y - point.Y; point = newpoint; Canvas.SetLeft(rt, Canvas.GetLeft(rt) + leftmove); Canvas.SetTop(rt, Canvas.GetTop(rt) + topmove); } private void myGrid_Drop(object sender, DragEventArgs e) { rt.Visibility = Visibility.Collapsed; Canvas.SetLeft(btn, Canvas.GetLeft(rt)); Canvas.SetTop(btn, Canvas.GetTop(rt)); } }