1,自定义行为:
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;
namespace CustomBehaviorsLibrary
{
public class DragInCanvasBehavior:Behavior<UIElement>
{
Canvas canvas;
bool flag = false;
Point offset;
protected override void OnAttached()
{
base.OnAttached();
//注册事件
this.AssociatedObject.MouseDown += AssociatedObject_MouseDown;
this.AssociatedObject.MouseMove += AssociatedObject_MouseMove;
this.AssociatedObject.MouseUp += AssociatedObject_MouseUp;
}
private void AssociatedObject_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (flag)
{
this.AssociatedObject.ReleaseMouseCapture();
flag = false;
}
}
private void AssociatedObject_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
if (flag)
{
Point curPoint = e.GetPosition(canvas);
curPoint.Offset(offset.X, offset.Y);
Canvas.SetLeft(this.AssociatedObject, curPoint.X);
Canvas.SetTop(this.AssociatedObject, curPoint.Y);
}
}
private void AssociatedObject_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
//获取当前对象的父容器
if (canvas == null)
{
DependencyObject parent = LogicalTreeHelper.GetParent(this.AssociatedObject);
if(parent is Canvas)
{
canvas = parent as Canvas;
}
else
{
throw new ArgumentException("只支持在Canvas中进行拖拽行为");
}
}
Point p = e.GetPosition(this.AssociatedObject);
offset = new Point(-p.X, -p.Y);
flag = true;
//获取鼠标
this.AssociatedObject.CaptureMouse();
}
protected override void OnDetaching()
{
base.OnDetaching();
//移除事件
this.AssociatedObject.MouseUp -= AssociatedObject_MouseUp;
this.AssociatedObject.MouseDown -= AssociatedObject_MouseDown;
this.AssociatedObject.MouseMove -= AssociatedObject_MouseMove;
}
}
}
2,使用自定义行为:
<Window x:Class="行为.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:行为"
mc:Ignorable="d"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:custom="clr-namespace:CustomBehaviorsLibrary;assembly=CustomBehaviorsLibrary"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="337*"/>
<ColumnDefinition Width="180*"/>
</Grid.ColumnDefinitions>
<Canvas Margin="10" Background="LightGray" >
<Rectangle Fill="AliceBlue" Canvas.Left="10" Canvas.Top="20" Width="40" Height="20"></Rectangle>
<Ellipse Fill="AntiqueWhite" Canvas.Left="50" Canvas.Top="40" Width="100" Height="50">
<i:Interaction.Behaviors>
<custom:DragInCanvasBehavior></custom:DragInCanvasBehavior>
</i:Interaction.Behaviors>
</Ellipse>
<Polygon Fill="GreenYellow" Canvas.Left="100" Canvas.Top="100" Width="100" Height="100" Points="12,23 40,40 100,100 12,40" ></Polygon>
</Canvas>
</Grid>
</Window>