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
    {
        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之行为)