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()方法,代碼如下:
protected override void OnAttached() { base.OnAttached(); this.AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown; this.AssociatedObject.MouseLeftButtonUp += AssociatedObject_MouseLeftButtonUp; this.AssociatedObject.MouseMove += AssociatedObject_MouseMove; } /// <summary> /// Behavior.OnDetaching(),移出事件處理程序 /// </summary> protected override void OnDetaching() { base.OnDetaching(); this.AssociatedObject.MouseLeftButtonDown -= AssociatedObject_MouseLeftButtonDown; this.AssociatedObject.MouseLeftButtonUp -= AssociatedObject_MouseLeftButtonUp; this.AssociatedObject.MouseMove -= AssociatedObject_MouseMove; }
(3)添加的行為的事件處理程序
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) { AssociatedObject.ReleaseMouseCapture(); isDragging = false; } }
(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) 運行效果
本欄目