public class ResizeBehavior { // 附加属性用于标识控件是否可调整大小 public static readonly DependencyProperty IsResizableProperty = DependencyProperty.RegisterAttached("IsResizable", typeof(bool), typeof(ResizeBehavior), new PropertyMetadata(false, OnIsResizableChanged)); public static bool GetIsResizable(DependencyObject obj) { return (bool)obj.GetValue(IsResizableProperty); } public static void SetIsResizable(DependencyObject obj, bool value) { obj.SetValue(IsResizableProperty, value); } // 当 IsResizable 附加属性发生改变时触发的回调方法 private static void OnIsResizableChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is FrameworkElement element) { if ((bool)e.NewValue) { element.MouseLeftButtonDown += Element_MouseLeftButtonDown; element.MouseMove += Element_MouseMove; element.MouseLeftButtonUp += Element_MouseLeftButtonUp; } else { element.MouseLeftButtonDown -= Element_MouseLeftButtonDown; element.MouseMove -= Element_MouseMove; element.MouseLeftButtonUp -= Element_MouseLeftButtonUp; } } } private static bool isResizing = false; private static Point originalMousePos; private static double originalWidth; private static FrameworkElement resizingElement = null!; // 鼠标左键按下时触发的事件处理程序 private static void Element_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { isResizing = true; originalMousePos = e.GetPosition(null); originalWidth = ((FrameworkElement)sender).ActualWidth; resizingElement = (FrameworkElement)sender; // 添加对鼠标左键按下事件的处理 if (resizingElement != null) { resizingElement.CaptureMouse(); // 捕获鼠标 } } // 鼠标移动时触发的事件处理程序 private static void Element_MouseMove(object sender, MouseEventArgs e) { if (isResizing && resizingElement != null) { Point currentMousePos = e.GetPosition(null); double delta = currentMousePos.X - originalMousePos.X; double newWidth = originalWidth + delta; if (newWidth > 0) { resizingElement.Width = newWidth; } } } // 鼠标左键释放时触发的事件处理程序 private static void Element_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { if (isResizing && resizingElement != null) { isResizing = false; resizingElement.ReleaseMouseCapture(); // 释放鼠标捕获 resizingElement = null!; } } }
<Border service:ResizeBehavior.IsResizable="True" BorderThickness="2" BorderBrush="Gray" Cursor="SizeWE"></Border>