Canvas布局下使用附加属性使控件岁鼠标移动
Posted yeshuimaowei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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布局下使用附加属性使控件岁鼠标移动的主要内容,如果未能解决你的问题,请参考以下文章