资料来源:WPF编程宝典P272
1、获取行为的支持,安装Expression Blend 4
SDK(http://www.microsoft.com/zh-cn/download/details.aspx?id=10801) 。
2、创建行为库
(1)创建一个Class Project,添加WPF必备的以及WPF中支持行为必备的dll文件。

其中,System.Windows.Interactivity.dll组件在目录(需要安装Blend SDKs):C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.0\Libraries。

(2)创建DragInCanvasBehavior.cs,继承类Behavior<UIElement>,overrideBehavior<UIElement>得OnAttached()和OnDetaching()方法,代码如下:。
1 protected override void OnAttached() 2 { 3 base.OnAttached(); 4 this.AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown; 5 this.AssociatedObject.MouseLeftButtonUp += AssociatedObject_MouseLeftButtonUp; 6 this.AssociatedObject.MouseMove += AssociatedObject_MouseMove; 7 } 8 9 /// <summary> 10 /// Behavior.OnDetaching(),移出事件处理程序 11 /// </summary> 12 protected override void OnDetaching() 13 { 14 base.OnDetaching(); 15 this.AssociatedObject.MouseLeftButtonDown -= AssociatedObject_MouseLeftButtonDown; 16 this.AssociatedObject.MouseLeftButtonUp -= AssociatedObject_MouseLeftButtonUp; 17 this.AssociatedObject.MouseMove -= AssociatedObject_MouseMove; 18 }
(3)添加的行为的事件处理程序
1 private void AssociatedObject_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) 2 { 3 if (canvas == null) 4 { 5 canvas = VisualTreeHelper.GetParent(this.AssociatedObject) as Canvas; 6 } 7 if (canvas != null) 8 { 9 isDragging = true; 10 mouseOffset = e.GetPosition(this.AssociatedObject); 11 AssociatedObject.CaptureMouse(); 12 } 13 } 14 15 private void AssociatedObject_MouseMove(object sender, System.Windows.Input.MouseEventArgs e) 16 { 17 if (canvas != null && isDragging == true) 18 { 19 Point p = e.GetPosition(canvas); 20 AssociatedObject.SetValue(Canvas.TopProperty, p.Y - mouseOffset.Y); 21 AssociatedObject.SetValue(Canvas.LeftProperty, p.X - mouseOffset.X); 22 } 23 } 24 25 private void AssociatedObject_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e) 26 { 27 if (isDragging) 28 { 29 AssociatedObject.ReleaseMouseCapture(); 30 isDragging = false; 31 } 32 }
(4)使用行为
在WPF Application中添加Class Library和System.Windows.Interactivity.dll
① 添加XML映射名称空间
② 使用代码
<Canvas > <Label x:Name="label" Content="我是中国人" Background="LemonChiffon" Width="240" HorizontalContentAlignment="Center" FontSize="16"> <i:Interaction.Behaviors> <custom:DragInCanvasBehavior></custom:DragInCanvasBehavior> </i:Interaction.Behaviors> </Label> <Label x:Name="label2" Content="我是中国人" Background="LemonChiffon" Width="240" HorizontalContentAlignment="Center" FontSize="16"> <i:Interaction.Behaviors> <custom:DragInCanvasBehavior></custom:DragInCanvasBehavior> </i:Interaction.Behaviors> </Label> </Canvas>
(5) 运行效果
技术交流:
QQ:892334612