using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Media;
namespace Demo1024
{
public class DragInCanvasBehavior:Behavior<UIElement>
{
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.MouseLeftButtonDown -= AssociatedObject_MouseLeftButtonDown;
AssociatedObject.MouseMove -= AssociatedObject_MouseMove;
AssociatedObject.PreviewMouseLeftButtonUp -= AssociatedObject_PreviewMouseLeftButtonUp;
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown;
AssociatedObject.MouseMove += AssociatedObject_MouseMove;
AssociatedObject.PreviewMouseLeftButtonUp += AssociatedObject_PreviewMouseLeftButtonUp;
}
private void AssociatedObject_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (isDragging)
{
AssociatedObject.ReleaseMouseCapture();
isDragging = false;
}
}
private void AssociatedObject_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
if (isDragging)
{
Point point = e.GetPosition(canvas);
AssociatedObject.SetValue(Canvas.TopProperty, point.Y-mouseOffset.Y);
AssociatedObject.SetValue(Canvas.LeftProperty, point.X-mouseOffset.X);
}
}
private Canvas canvas;
private bool isDragging = false;
private Point mouseOffset;
private void AssociatedObject_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (canvas==null)
{
canvas = (Canvas)VisualTreeHelper.GetParent(this.AssociatedObject);
}
isDragging = true;
mouseOffset = e.GetPosition(AssociatedObject);
AssociatedObject.CaptureMouse();
}
}
}
<Window x:Class="Demo1024.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Demo1024"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
mc:Ignorable="d"
Title="MainWindow" Height="774.398" Width="821.687">
<Grid>
<StackPanel>
<Canvas Background="AliceBlue">
<Rectangle Canvas.Left="10" Canvas.Top="10" Fill="Yellow" Height="60" Width="40"/>
<Ellipse Canvas.Left="10" Canvas.Top="70" Fill="Blue" Height="80" Width="60">
<i:Interaction.Behaviors>
<local:DragInCanvasBehavior/>
</i:Interaction.Behaviors>
</Ellipse>
<Ellipse Canvas.Left="80" Canvas.Top="70" Fill="OrangeRed" Height="40" Width="80">
<i:Interaction.Behaviors>
<local:DragInCanvasBehavior/>
</i:Interaction.Behaviors>
</Ellipse>
</Canvas>
</StackPanel>
</Grid>
</Window>