拖放形状

我在stackpanel中有一个矩形形状,我想用WPF拖放到网格中! 如果有人可以帮助我,我很感激吗? 谢谢大家。

一个非常简单的实现如下。 它只是处理鼠标按钮向下/向上/移动Rectangle事件,以便与鼠标移动一起定位它。 没有错误检查,也没有任何东西阻止用户将矩形拖离Canvas并将其留在那里。

XAML:


        

代码背后:


 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApplication6 { ///  /// Interaction logic for MainWindow.xaml ///  public partial class MainWindow : Window { private bool _isRectDragInProg; public MainWindow() { InitializeComponent(); } private void rect_MouseLeftButtonDown( object sender, MouseButtonEventArgs e ) { _isRectDragInProg = true; rect.CaptureMouse(); } private void rect_MouseLeftButtonUp( object sender, MouseButtonEventArgs e ) { _isRectDragInProg = false; rect.ReleaseMouseCapture(); } private void rect_MouseMove( object sender, MouseEventArgs e ) { if( !_isRectDragInProg ) return; // get the position of the mouse relative to the Canvas var mousePos = e.GetPosition(canvas); // center the rect on the mouse double left = mousePos.X - (rect.ActualWidth / 2); double top = mousePos.Y - (rect.ActualHeight / 2); Canvas.SetLeft( rect, left ); Canvas.SetTop( rect, top ); } } } 

为了在项目控件中实现拖放,其中项目由canvas以外的任何东西布局,那么我强烈建议您查看Bea Stollnitz解决方案 。 这是一个完全可重用的解决方案,可以使用附加属性在任何项目控件之间进行拖放。

更新:鉴于Bea的博客已经消失,还有其他post基于她仍然可用的解决方案:

  1. https://www.codeproject.com/Articles/43614/Drag-and-Drop-in-WPF
  2. http://blogarchive.claritycon.com/blog/2009/03/generic-wpf-drag-and-drop-adorner
  3. https://siderite.blogspot.com/2011/01/mvvm-drag-and-drop-part-1.html