I have a rectangle shape in a stackpanel and i want to drag and drop in a grid with the mouse using WPF! I appreciate it if someone can help me? Thanks to everyone.
A very simple implementation follows. It simply handles the Mouse button down/up/move events of the Rectangle
in order to position it along with mouse movement. There is no error checking and nothing to prevent the user from dragging the rectangle off of the Canvas and leaving it there.
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>
Code Behind:
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 );
}
}
}
For implementing drag and drop in an items control where the items are laid out by anything other than a canvas, then I would highly recommend checking out Bea Stollnitz solution. This is a completely reusable solution to drag and drop between any items control using attached properties.
Update: given that Bea's blog is gone, there are other posts that are based on her solution still available:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With