1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Windows; 7 using System.Windows.Controls; 8 using System.Windows.Data; 9 using System.Windows.Documents;10 using System.Windows.Input;11 using System.Windows.Media;12 using System.Windows.Media.Imaging;13 using System.Windows.Navigation;14 using System.Windows.Shapes;15 16 namespace WpfApplication117 {18 ///19 /// MainWindow.xaml 的交互逻辑20 /// 21 public partial class MainWindow : Window22 {23 public MainWindow()24 {25 InitializeComponent();26 Binding binding = new Binding();27 binding.Source = main_grid;28 binding.Path = new PropertyPath("Margin");29 binding.Mode = BindingMode.TwoWay;30 binding.Converter = new MarginConverter();31 binding.ConverterParameter = main_grid.Width;32 sub_grid.SetBinding(Grid.MarginProperty, binding);33 }34 35 public class MarginConverter : IValueConverter36 {37 38 public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)39 {40 Thickness margin = (Thickness)value;41 double width = (double)parameter;42 return new Thickness(margin.Left + width, margin.Top -30, 0, 0);43 }44 45 public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)46 {47 Thickness margin = (Thickness)value;48 double width = (double)parameter;49 return new Thickness(margin.Left - width, margin.Top + 30, 0, 0);50 }51 }52 53 //选中控件的鼠标位置偏移量54 Point targetPoint;55 56 private void canvas_MouseDown(object sender, MouseButtonEventArgs e)57 {58 var targetElement = e.Source as IInputElement;59 if (targetElement != null)60 {61 targetPoint = e.GetPosition(targetElement);62 //开始捕获鼠标63 targetElement.CaptureMouse();64 }65 }66 67 private void canvas_MouseUp(object sender, MouseButtonEventArgs e)68 {69 //取消捕获鼠标70 Mouse.Capture(null);71 }72 73 private void canvas_MouseMove(object sender, MouseEventArgs e)74 {75 //确定鼠标左键处于按下状态并且有元素被选中76 var targetElement = Mouse.Captured as Grid;77 if (e.LeftButton == MouseButtonState.Pressed && targetElement != null)78 {79 var pCanvas = e.GetPosition(canvas);80 //设置最终位置81 targetElement.Margin = new Thickness(pCanvas.X - targetPoint.X, pCanvas.Y - targetPoint.Y, 0, 0);82 }83 }84 }85 }
19 21