1, obtain the behavior support, installs the expression Blend 4 SDK (http://www.microsoft.com/zh-cn/download/details.aspx?id=10801).
2. Create a behavior Library
(1) Create a class Project to add the WPF prerequisites and the DLL files that support the behavior prerequisites in WPF.
Where the System.Windows.Interactivity.dll component is in the directory (you need to install Blend SDKs): C:\Program Files (x86) \microsoft Sdks\expression\blend\. Netframework\v4.0\libraries.
(2) Create DragInCanvasBehavior.cs, inherit class behavior<uielement>,overridebehavior<uielement> get Onattached () and the Ondetaching () method, the code is as follows:
protected override void Onattached ()
{
base. Onattached ();
This. Associatedobject.mouseleftbuttondown + = Associatedobject_mouseleftbuttondown;
This. Associatedobject.mouseleftbuttonup + = Associatedobject_mouseleftbuttonup;
This. Associatedobject.mousemove + + associatedobject_mousemove;
}
<summary>
///behavior.ondetaching (), removing event handlers
///</summary>
protected override void Ondetaching ()
{
base. Ondetaching ();
This. Associatedobject.mouseleftbuttondown-= Associatedobject_mouseleftbuttondown;
This. Associatedobject.mouseleftbuttonup-= Associatedobject_mouseleftbuttonup;
This. Associatedobject.mousemove-= Associatedobject_mousemove;
}
(3) Event handlers for the added behavior
private void Associatedobject_mouseleftbuttondown (object sender, System.Windows.Input.MouseButtonEventArgs e) { if (canvas = = NULL) {canvas = Visualtreehelper.getparent (this.
Associatedobject) as Canvas;
} if (canvas!= null) {isdragging = true; Mouseoffset = E.getposition (this.
Associatedobject);
Associatedobject.capturemouse ();
}} private void Associatedobject_mousemove (object sender, System.Windows.Input.MouseEventArgs e) {if (canvas!= null && isdragging = = True) {Point P = e.getposition
(canvas);
Associatedobject.setvalue (Canvas.topproperty, P.Y-MOUSEOFFSET.Y);
Associatedobject.setvalue (Canvas.leftproperty, p.x-mouseoffset.x); }} private void Associatedobject_mouseleftbuttonup (object sender,System.Windows.Input.MouseButtonEventArgs e) {if (isdragging) {Associate
Dobject.releasemousecapture ();
Isdragging = false; }
}