2011-05-26 77 views
2

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

+2

有你尝试过任何东西,并有一些代码分享有问题,或者是你不知道从哪里开始?如果它的后者:http://msdn.microsoft.com/en-us/library/ms742859.aspx – schummbo 2011-05-26 18:12:47

回答

7

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

XAML:


<Window x:Class="WpfApplication6.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <Canvas Name="canvas"> 
      <Rectangle 
       Name="rect" 
       Width="50" 
       Height="50" 
       Canvas.Left="0" 
       Canvas.Top="0" 
       Fill="Red" 
       MouseLeftButtonDown="rect_MouseLeftButtonDown" 
       MouseLeftButtonUp="rect_MouseLeftButtonUp" 
       MouseMove="rect_MouseMove" 
       /> 
     </Canvas> 
    </Grid> 
</Window> 

代码背后:


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 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    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); 
     } 
    } 
} 
0

对于在项目实施的拖放控制,其中项都受到比画布以外的任何布局,那么我强烈建议检查Bea Stollnitz solution。这是一个完全可重用的解决方案,用于在使用附加属性的任何项目控件之间拖放。

更新:鉴于衣的博客走了,但是也有一些基于她的解决方案仍然可用其他职位:

  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
+0

链接断开。任何回忆解决方案? – 2016-05-08 22:50:53

+0

还有其他几个人参考她的工作。 https://blogs.claritycon.com/blog/2009/03/generic-wpf-drag-and-drop-adorner/ – 2016-05-17 03:05:41