码迷,mamicode.com
首页 > Windows程序 > 详细

WPF之行为

时间:2019-12-22 00:21:56      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:code   parent   override   rgs   位置   over   cte   div   ase   

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

标签:code   parent   override   rgs   位置   over   cte   div   ase   

原文地址:https://www.cnblogs.com/qcst123/p/12071510.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!