WPF之行为
Posted qcst123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF之行为相关的知识,希望对你有一定的参考价值。
Behavior的运用扩展了”交互“功能,以下记录示例:
在的项目中添加两个引用:
Microsoft.Expression.Interactions.dll
System.Windows.Interactivity.dll
<Canvas> <Rectangle Height="40" Width="80" Canvas.Left="100" Canvas.Top="50" Fill="Aqua"> <i:Interaction.Behaviors> <local:DragInCanvsBehavior/> </i:Interaction.Behaviors> </Rectangle> <Ellipse Height="40" Width="80" Fill="AntiqueWhite"/> </Canvas>
主要是实现OnAttached()和OnDetaching()方法,在OnAttached()方法中关联事件处理程序,在OnDetaching()中移除事件处理程序。
public class DragInCanvsBehavior : Behavior<UIElement> { private Canvas m_Canvas; private bool m_IsDraging; private Point m_PositionOffset; protected override void OnAttached() { base.OnAttached(); AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown; AssociatedObject.MouseMove += AssociatedObject_MouseMove; AssociatedObject.MouseLeftButtonUp += AssociatedObject_MouseLeftButtonUp; } void AssociatedObject_MouseMove(object sender, System.Windows.Input.MouseEventArgs e) { if (!m_IsDraging) return; Point mouseposition = e.GetPosition(m_Canvas);//得到鼠标相对于Canvas对象的位置 AssociatedObject.SetValue(Canvas.LeftProperty, mouseposition.X - m_PositionOffset.X);//获得需要移动的相对距离 AssociatedObject.SetValue(Canvas.TopProperty, mouseposition.Y - m_PositionOffset.Y); } void AssociatedObject_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { if (!m_IsDraging) return; m_IsDraging = false; AssociatedObject.ReleaseMouseCapture();//释放鼠标的捕获 } void AssociatedObject_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { if (m_Canvas == null) m_Canvas = (Canvas)VisualTreeHelper.GetParent(AssociatedObject);//捕捉到附加对象的父对象 m_IsDraging = true; m_PositionOffset = e.GetPosition(AssociatedObject);//得到鼠标相对于附加对象的位置 AssociatedObject.CaptureMouse();//鼠标捕获到元素 } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.MouseLeftButtonDown -= AssociatedObject_MouseLeftButtonDown; AssociatedObject.MouseMove -= AssociatedObject_MouseMove; AssociatedObject.MouseLeftButtonUp -= AssociatedObject_MouseLeftButtonUp; } }
以上是关于WPF之行为的主要内容,如果未能解决你的问题,请参考以下文章