码迷,mamicode.com
首页 > 移动开发 > 详细

Canvas布局下使用附加属性使控件岁鼠标移动

时间:2018-09-28 12:38:20      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:使用   gis   register   system   obj   view   分享图片   3.1   width   

定义附加属性
public class MoveBehavior { public static readonly DependencyProperty IsMoveAbleProperty = DependencyProperty.RegisterAttached("IsMoveAble", typeof(bool), typeof(MoveBehavior),new PropertyMetadata(false, OnEnableMoveChanged)); public static bool GetIsMoveAble(DependencyObject obj) { return (bool)obj.GetValue(IsMoveAbleProperty); } public static void SetIsMoveAble(DependencyObject obj,bool value) { obj.SetValue(IsMoveAbleProperty, value); } public static void OnEnableMoveChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var element = d as FrameworkElement; if (d!=null&& GetIsMoveAble(d)) { element.PreviewMouseDown += Element_MouseDown; element.PreviewMouseUp += Element_MouseUp; element.PreviewMouseMove += Element_MouseMove; } } private static bool isCaptured = false; private static void Element_MouseMove(object sender, System.Windows.Input.MouseEventArgs e) { var element = sender as FrameworkElement; if (element == null) return; var parent = VisualTreeHelper.GetParent(element) as FrameworkElement; if (parent == null) return; if (!isCaptured) return; var p = e.GetPosition(parent); Canvas.SetTop(element, p.Y - element.ActualWidth / 2); Canvas.SetLeft(element, p.X - element.ActualHeight / 2); } private static void Element_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { isCaptured = false; (sender as FrameworkElement).ReleaseMouseCapture(); } private static void Element_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { isCaptured = true; (sender as FrameworkElement).CaptureMouse(); } }

使用如下:

<Canvas>
        <Ellipse Width="50" Height="50" Fill="Red" x:Name="el"
               local:MoveBehavior.IsMoveAble="True"  ></Ellipse>
        <Button local:MoveBehavior.IsMoveAble="False" Click="Button_Click_1" Content="Button" Canvas.Left="303.112" Canvas.Top="196.833" Width="75" Height="47.005"/>
    </Canvas>

 效果图:

技术分享图片

 

Canvas布局下使用附加属性使控件岁鼠标移动

标签:使用   gis   register   system   obj   view   分享图片   3.1   width   

原文地址:https://www.cnblogs.com/yeshuimaowei/p/9717397.html

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