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

定义附加属性
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布局下使用附加属性使控件岁鼠标移动

 

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

上一篇:c-lodop云打印实现手机打印 JS语句打印


下一篇:pandas的apply操作