Microsoft 的 Expression Blend Behaviors 就是这样做的。要实现和使用您自己的行为,您不需要 Expression Blend,只需要可下载的 SDK。
它的工作方式是你实现 Behavior where T : DependencyObject。该类有两个可覆盖的方法 OnAttach() 和 OnDetach(),您可以将它们连接和取消连接到您的事件,并将上述逻辑放入行为中。如果你要命名你的类 DrawRectangleBehavior,那么你需要做的就是:
....
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
....
<Canvas>
<i:Interaction.Behaviors>
<myBlend:DrawRectangleBehavior />
</i:Interaction.Behaviors>
</Canvas>
和行为(我没有测试这个)
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Media;
using System.Windows.Shapes;
namespace MyCompany.Common.Behaviors
{
public class DrawRectangleBehavior : Behavior<Canvas>
{
Point StartPoint;
Shape shape;
protected override void OnAttached()
{
AssociatedObject.PreviewMouseLeftButtonDown += OnMouseLeftButtonDown;
AssociatedObject.PreviewMouseMove += OnMouseMove;
AssociatedObject.MouseLeave += OnMouseLeave;
}
protected override void OnDetaching()
{
AssociatedObject.PreviewMouseLeftButtonDown -= OnMouseLeftButtonDown;
AssociatedObject.PreviewMouseMove -= OnMouseMove;
AssociatedObject.MouseLeave -= OnMouseLeave;
}
protected void OnMouseLeftButtonDown(object o, MouseButtonEventArgs e)
{
StartPoint = e.GetPosition(AssociatedObject);
shape = new Rectangle();
shape.Fill = Brushes.Transparent;
shape.Stroke = Brushes.Black;
shape.StrokeThickness = 1;
AssociatedObject.Children.Add(shape);
}
protected void OnMouseMove(object o, MouseEventArgs e)
{
Point endpoint = e.GetPosition(AssociatedObject);
double left = Math.Min(endpoint.X, StartPoint.X);
double top = Math.Min(endpoint.Y, StartPoint.Y);
shape.Margin = new Thickness(left, top, 0, 0);
shape.Width = Math.Abs(endpoint.X - StartPoint.X);
shape.Height = Math.Abs(endpoint.Y - StartPoint.Y);
shape.Stroke = Brushes.Black;
shape.StrokeThickness = 2;
}
protected void OnMouseLeave(object o, MouseEventArgs e)
{
//end
}
}
}
你有一段可重用的代码。
请看以下教程WPF 教程 | 混合行为
以及下面的下载链接Expression Blend SDK