C# wpf 实现任意控件(包括窗口)更多调整大小功能

WPF拖动改变大小系列

第一节 Grid内控件拖动调整大小
第二节 Canvas内控件拖动调整大小
第三节 窗口拖动调整大小
第四节 附加属性实现拖动调整大小
第五章 拓展更多调整大小功能(本章)


文章目录

  • WPF拖动改变大小系列
  • 前言
  • 一、添加的功能
    • 1、任意控件DragResize
    • 2、边界限制
    • 3、交叉拖动
      • (1)判断控件边界
      • (2)固定到控件边界
      • (3)事件转移
    • 4、拖动点模板
    • 5、拖动点容器模板
    • 6、整体模板
    • 7、窗口平滑拖动
    • 8、拖动事件
    • 9、其他功能
      • (1)适应MinWidth、MinHeight
      • (2)适应MaxWidth、MaxHeight
      • (3)适配任意dpi
  • 二、完整代码
  • 三、使用示例
    • 0、基础功能
      • (1)、引用命名空间
      • (2)、使用附加属性
    • 1、DragResize
    • 2、边界限制
    • 3、交叉拖动
    • 4、拖动点布局模板
      • (1)自定义圆点
      • (2)4个顶点
      • (3)单独定制每个点
    • 5、拖动点容器模板
      • (1)无Margin
      • (2)设置Margin
    • 6、整体模板
    • 7、窗口平滑拖动
    • 8、拖动事件
    • 9、其他功能
      • (1)适应MinWidth、MinHeight
      • (2)适应MaxWidth、MaxHeight
  • 总结


前言

上一章我们已经实现了任意控件统一的拖动调整功能,能够方便的给任意控件设置拖动调整大小。开发过程中发现还是有些功能可以继续拓展的,比如cs代码触发拖动、自定义模板、交叉拖动、限制拖动范围等功能。有功能实现起来不算太容易,却很有实用价值。


一、添加的功能

在第四章基础上添加了如下功能。

1、任意控件DragResize

我们知道wpf的Window有DragMove功能,在鼠标左键按下事件中调用此方法就能实现拖动功能很方便。对于调整大小也可以实现类似的DragResize功能, 实际效果和点击画板拖出一个形状差不多。

代码示例如下:

 /// <summary>/// 手动触发拖动改变大小,与Window.DragMove类似,只能在鼠标左键按下时调用。/// 实际效果和点击画板拖出一个形状差不多。/// 此方法为拓展方法,FrameworkElement的子类控件(即有宽高属性的控件)都可以调用此方法。/// </summary>/// <param name="elememt"></param>/// <returns>返回Task,await等待拖动完成</returns>/// <exception cref="InvalidOperationException"></exception>public static async Task DragResize(this FrameworkElement elememt){if (Mouse.LeftButton != MouseButtonState.Pressed){throw new InvalidOperationException("Left button down to call this method");}if (elememt.Parent == null && elememt is not Window){throw new InvalidOperationException("Element should be on the visual tree");}//生成Resizeable对象,第四章完整代码中。//获取右下角Thumb//手动触发Thumb拖动事件//等待拖动完成}

2、边界限制

添加一个IsResizeInBounds附加属性,表示拖动范围是否在父控件内。
代码示例如下:

public static bool GetIsResizeInBounds(DependencyObject obj)
{return (bool)obj.GetValue(IsResizeInBoundsProperty);
}public static void SetIsResizeInBounds(DependencyObject obj, bool value)
{obj.SetValue(IsResizeInBoundsProperty, value);
}/// <summary>
/// 是否在父控件范围内拖动
/// </summary>
public static readonly DependencyProperty IsResizeInBoundsProperty =DependencyProperty.RegisterAttached("IsResizeInBounds", typeof(bool), typeof(Resize), new PropertyMetadata(false));

第四章的拖动逻辑中添加相应的限制功能,本质上就是判断如果超出边界则控件刚好依附在边界上,代码如下:

 var dx = left - margin.Left;var dy = top - margin.Top;if (GetIsResizeInBounds(c)){var pos = c.GetPosition();var parent = _resizeTarget.Parent as FrameworkElement;Size size;if (parent == null){size.Width = SystemParameters.PrimaryScreenWidth;size.Height = SystemParameters.PrimaryScreenHeight;}else{size.Width = parent.ActualWidth;size.Height = parent.ActualHeight;}if (pos.X + dx < 0){left = -pos.X + margin.Left;width = pos.X + c.ActualWidth;}else if (pos.X + dx + width > size.Width){width = size.Width - pos.X;right = margin.Right + c.ActualWidth - width;}if (pos.Y + dy < 0){top = -pos.Y + margin.Top;height = pos.Y + c.ActualHeight;}else if (pos.Y + dy + height > size.Height){height = size.Height - pos.Y;bottom = margin.Bottom + c.ActualHeight - height;}}                

3、交叉拖动

交叉拖动是曾经用gdi画图时会出现的一种情况,gdi绘制的宽高可以为负数,所以可以直接穿过起点反向拖动也能绘制出图形。在wpf中的控件是不支持宽高负数的,所以我们需要用其他方式实现。
下列步骤以横向为例:

(1)判断控件边界

 if (width < 0

(2)固定到控件边界

SetTargetMargin为前3章的集合,根据不同控件类型比如Window是设置Left、Top、Grid则设置Margin等。minWidth是控件的MinWidth属性。margin参考第四张完整代码。

if (thumb.HorizontalAlignment == HorizontalAlignment.Left)
//左拖动点
{SetTargetMargin(new Thickness(margin.Left + c.Width - minWidth, margin.Top, margin.Right - c.Width + minWidth, margin.Bottom));
}
else
//右拖动点
{SetTargetMargin(new Thickness(margin.Left - c.Width + minWidth, margin.Top, margin.Right + c.Width - minWidth, margin.Bottom));
}

(3)事件转移

//当前拖动点触发鼠标弹起事件
MouseButtonEventArgs upEvent = new MouseButtonEventArgs(Mouse.PrimaryDevice, Environment.TickCount, MouseButton.Left)
{ RoutedEvent = UIElement.MouseLeftButtonUpEvent };
thumb.RaiseEvent(upEvent);
//反向拖动点触发鼠标按下事件
MouseButtonEventArgs downEvent = new MouseButtonEventArgs(Mouse.PrimaryDevice, Environment.TickCount, MouseButton.Left)
{ RoutedEvent = UIElement.MouseLeftButtonDownEvent };
t.RaiseEvent(downEvent);

4、拖动点模板

添加附加属性ThumbsTemplate

public static ControlTemplate GetThumbsTemplate(DependencyObject obj)
{return (ControlTemplate)obj.GetValue(ThumbsTemplateProperty);
}public static void SetThumbsTemplate(DependencyObject obj, ControlTemplate value)
{obj.SetValue(ThumbsTemplateProperty, value);
}/// <summary>
/// 拖动点的模板
/// </summary>
public static readonly DependencyProperty ThumbsTemplateProperty =DependencyProperty.RegisterAttached("ThumbsTemplate", typeof(ControlTemplate), typeof(Resize), new PropertyMetadata(null));

生成拖动点时会应用模板

var thumbsTemplate = GetThumbsTemplate(_resizeTarget);
thumb.Template = thumbsTemplate;

5、拖动点容器模板

拖动点的容器模板,主要用于设置margin调整拖动点的整体位置,添加附加属性ThumbsPanel。

 public static ItemsPanelTemplate GetThumbsPanel(DependencyObject obj){return (ItemsPanelTemplate)obj.GetValue(ThumbsPanelProperty);}public static void SetThumbsPanel(DependencyObject obj, ItemsPanelTemplate value){obj.SetValue(ThumbsPanelProperty, value);}/// <summary>/// 拖动点的容器,主要用于设置margin/// </summary>public static readonly DependencyProperty ThumbsPanelProperty =DependencyProperty.RegisterAttached("ThumbsPanel", typeof(ItemsPanelTemplate), typeof(Resize), new PropertyMetadata(null));

生成拖动点布局时会应用模板

var itemsPanel = GetThumbsPanel(_resizeTarget);
_defalutPanel.ItemsPanel = itemsPanel;

6、整体模板

拖动点模板和拖动点布局模板已经很大程度灵活了使用,如果需要更高的定制性,直接使用整体模板,整体模板赋值后拖动点模板和拖动点布局模板会失效。此功能与第四章的ResizeTemplate相同但名称改为Template。基本规则是第一级控件为容器、第二级控件为Thumb类型自动识别为拖动点,拖动方向由HorizontalAlignment和VerticalAlignment决定。

7、窗口平滑拖动

之所有要对窗口拖动平滑处理是因为,自定义的调整大小只能设置Window的Left、Top、Width、Height,当窗口进行左或上拖动时右或下会出现残影,这种情况通过SetWindowPos和MoveWindow也无法改善。在不使用窗口自带的拖动功能的情况下,目前笔者研究出的方法就是使用透明窗口全屏,控件模拟窗口进行拖动。当然这种实现的限制就是一定要透明窗口,AllowTransparency为true或者WindowChrome的GlassFrameThickness为-1。

因为这种实现还不是很完美对装饰器不兼容,所以提供IsWindowDragSmooth属性,可以打开和关闭功能。

public static bool GetIsWindowDragSmooth(DependencyObject obj)
{return (bool)obj.GetValue(IsWindowDragSmoothProperty);
}public static void SetIsWindowDragSmooth(DependencyObject obj, bool value)
{obj.SetValue(IsWindowDragSmoothProperty, value);
}/// <summary>
/// 拖拽窗口调整大小是否平滑处理,作用是避免拖拽窗口左上时右下闪烁。
/// 此属性只对窗口有效
/// 此属性为true时需要透明窗口才能生效,即AllowTransparency为true或者WindowChrome的GlassFrameThickness为-1。
/// 当前版本不兼容有装饰器的窗口,拖动中装饰器可能会显示在窗口外面。
/// </summary>
// Using a DependencyProperty as the backing store for IsWindowDragSmooth.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsWindowDragSmoothProperty =DependencyProperty.RegisterAttached("IsWindowDragSmooth", typeof(bool), typeof(Resize), new PropertyMetadata(false));

8、拖动事件

提供3个拖动事件,拖动开始、拖动变化、拖动结束。
代码示例如下:

/// <summary>
///  拖动开始事件
/// </summary>
public static readonly RoutedEvent DragResizeStartedEvent = EventManager.RegisterRoutedEvent("DragResizeStarted", RoutingStrategy.Direct, typeof(EventHandler<DragResizeStartedEventArgs>), typeof(Resize));
/// <summary>
/// 拖动变化事件
/// </summary>
public static readonly RoutedEvent DragResizeDeltaEvent = EventManager.RegisterRoutedEvent("DragResizeDelta", RoutingStrategy.Direct, typeof(EventHandler<DragResizeDeltaEventArgs>), typeof(Resize));
/// <summary>
/// 拖动结束事件
/// </summary>
public static readonly RoutedEvent DragResizeCompletedEvent = EventManager.RegisterRoutedEvent("DragResizeCompleted", RoutingStrategy.Direct, typeof(EventHandler<DragResizeCompletedEventArgs>), typeof(Resize));

9、其他功能

(1)适应MinWidth、MinHeight

在第四章完整带的基础上将边界判断修改为控件的MinWidth、MinHeight即可。
横向

if (width >= minWidth/*原本是0*/)
{//略
}

纵向与横向逻辑一致,修改对应变量即可,略

(2)适应MaxWidth、MaxHeight

超过了最大值需要进行修正示例如下
横向:

if (width > c.MaxWidth)
{if (thumb.HorizontalAlignment == HorizontalAlignment.Left){left += width - c.MaxWidth;right = margin.Right;}else{left = margin.Left;right += width - c.MaxWidth;}width = c.MaxWidth;
}

纵向与横向逻辑一致,修改对应变量即可,略。

(3)适配任意dpi

所有改变坐标以及大小的代码已经适配了任意dpi。
主要注意的就是PointToScreen得到的坐标需要dpi转换。
下列是获取dpi的方法。

static Point GetDpiFromVisual(Visual visual)
{var source = PresentationSource.FromVisual(visual);var dpiX = 96.0;var dpiY = 96.0;if (source?.CompositionTarget != null){dpiX = 96.0 * source.CompositionTarget.TransformToDevice.M11;dpiY = 96.0 * source.CompositionTarget.TransformToDevice.M22;}return new Point(dpiX, dpiY);
}

二、完整代码

vs2022 wpf .net 6.0 项目,包含了第四章的功能,不需要重复下载。
之后上传


三、使用示例

0、基础功能

这个是与第四章一致的基础功能。

(1)、引用命名空间

Window 的其他属性略

<Window xmlns:ac="clr-namespace:AC"/>

(2)、使用附加属性

需要某个控件可以拖动调整大小则

<Grid ac:Resize.IsResizeable="True" />

1、DragResize

DragResize需要在鼠标左键按下事件中使用,对已存在的控件或者动态生成控件使用。此方法不需要ac:Resize.IsResizeable="True"也可以使用。
xaml

<Window x:Class="WpfResize.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfResize"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"WindowStyle="None"ResizeMode="NoResize"><Grid x:Name="grid" Background="SeaGreen"  MouseLeftButtonDown="Window_MouseLeftButtonDown"/>
</Window>

因为是拓展方法,所以获取到控件对象直接调用DragResize即可。
cs

using AC;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;namespace WpfResize
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}private async void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e){//生成控件var border = new Border();border.Background = Brushes.Azure;border.Width = 0;border.Height = 0;//加入到容器grid.Children.Add(border);//拖出控件await border.DragResize();//如果宽高为0则移除if (border.Width == 0|| border.Height == 0){grid.Children.Remove(border);}}}
}

效果预览
注:qq录制鼠标出现了偏移
在这里插入图片描述

2、边界限制

设置ac:Resize.IsResizeInBounds="True"即可。边界限制的范围是父控件。
xaml

<Window x:Class="WpfResize.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfResize"xmlns:ac="clr-namespace:AC"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"WindowStyle="None"ResizeMode="NoResize"     ><Grid x:Name="grid" Background="SeaGreen"><Border BorderThickness="1" BorderBrush="White" Margin="40"><StackPanel><Border ac:Resize.IsResizeable="True" ac:Resize.IsResizeInBounds="False" Background="White" Height="100" Width="200"  CornerRadius="10" ><TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="不限制边界"></TextBlock></Border><Border ac:Resize.IsResizeable="True" ac:Resize.IsResizeInBounds="True"  Margin="0,20,0,0" Background="White" Height="100" Width="200"  CornerRadius="10" ><TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="限制边界"></TextBlock></Border></StackPanel></Border></Grid>
</Window>

效果预览
注:qq录制鼠标出现了偏移
在这里插入图片描述

3、交叉拖动

通过附加属性ac:Resize.IsAllowsCrossover设置是否交叉拖动,默认为true。
xaml

<Window x:Class="WpfResize.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfResize"xmlns:ac="clr-namespace:AC"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"WindowStyle="None"ResizeMode="NoResize"     ><Grid x:Name="grid" Background="SeaGreen"><StackPanel><Border  Margin="0,20,0,0"  ac:Resize.IsResizeable="True" ac:Resize.IsAllowsCrossover="False"  Background="White" Height="100" Width="200"  CornerRadius="10" ><TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="不允许交叉拖动"></TextBlock></Border><Border ac:Resize.IsResizeable="True" ac:Resize.IsAllowsCrossover="True"   Margin="0,20,0,0" Background="White" Height="100" Width="200"  CornerRadius="10" ><TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="允许交叉拖动"></TextBlock></Border></StackPanel></Grid>
</Window>

效果预览
注:qq录制鼠标出现了偏移
在这里插入图片描述

4、拖动点布局模板

通过ac:Resize.ThumbsTemplate设置拖动点模板

(1)自定义圆点

xaml

<Window x:Class="WpfResize.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfResize"xmlns:ac="clr-namespace:AC"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"  ><Grid x:Name="grid" Background="White"><Grid  Margin="0,20,0,0"  ac:Resize.IsResizeable="True" ac:Resize.IsAllowsCrossover="False"  Background="SeaGreen " Height="100" Width="200" ><ac:Resize.ThumbsTemplate><ControlTemplate  ><Border BorderBrush="Gray" BorderThickness="2" CornerRadius="8"  Background="White" Width="16" Height="16"/></ControlTemplate></ac:Resize.ThumbsTemplate><TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" Text="自定义拖动点模板"></TextBlock></Grid></Grid>
</Window>

效果预览
在这里插入图片描述

(2)4个顶点

xaml

<Window x:Class="WpfResize.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfResize"xmlns:ac="clr-namespace:AC"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"  WindowStyle="None"ResizeMode="NoResize"><Grid x:Name="grid" Background="White"><Grid  Margin="0,20,0,0"  ac:Resize.IsResizeable="True" ac:Resize.IsAllowsCrossover="False"  Background="SeaGreen " Height="100" Width="200" ><ac:Resize.ThumbsTemplate><ControlTemplate ><Border x:Name="brd" BorderBrush="Gray" BorderThickness="2" CornerRadius="8"  Background="White" Width="16" Height="16"/><!--通过触发器隐藏4条边上的点--><ControlTemplate.Triggers><!--左右两条边上的点--><Trigger Property="HorizontalAlignment" Value="Stretch"><Setter TargetName="brd" Property="Visibility" Value="Collapsed" ></Setter></Trigger><!--上下两条边上的点--><Trigger Property="VerticalAlignment" Value="Stretch"><Setter TargetName="brd" Property="Visibility" Value="Collapsed" ></Setter></Trigger></ControlTemplate.Triggers></ControlTemplate></ac:Resize.ThumbsTemplate><TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" Text="自定义拖动点模板"></TextBlock></Grid></Grid>
</Window>

效果预览
在这里插入图片描述

(3)单独定制每个点

通过MultiTrigger触发器来区分每个点。
xaml

<Window x:Class="WpfResize.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfResize"xmlns:ac="clr-namespace:AC"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"  WindowStyle="None"ResizeMode="NoResize"><Grid x:Name="grid" Background="White"><Grid  Margin="0,20,0,0"  ac:Resize.IsResizeable="True" ac:Resize.IsAllowsCrossover="False"  Background="SeaGreen" Height="100" Width="200" ><ac:Resize.ThumbsTemplate><ControlTemplate ><Border x:Name="brd" BorderBrush="Gray" BorderThickness="2" CornerRadius="8"  Background="White" Width="16" Height="16"/><ControlTemplate.Triggers><!--左上--><MultiTrigger><MultiTrigger.Conditions><Condition Property="HorizontalAlignment" Value="Left" ></Condition><Condition Property="VerticalAlignment" Value="Top" ></Condition></MultiTrigger.Conditions><Setter TargetName="brd" Property="BorderBrush" Value="Aqua"></Setter></MultiTrigger><!--右上--><MultiTrigger><MultiTrigger.Conditions><Condition Property="HorizontalAlignment" Value="Right" ></Condition><Condition Property="VerticalAlignment" Value="Top" ></Condition></MultiTrigger.Conditions><Setter TargetName="brd" Property="BorderBrush" Value="DarkGoldenrod"></Setter></MultiTrigger><!--右下--><MultiTrigger><MultiTrigger.Conditions><Condition Property="HorizontalAlignment" Value="Right" ></Condition><Condition Property="VerticalAlignment" Value="Bottom" ></Condition></MultiTrigger.Conditions><Setter TargetName="brd" Property="BorderBrush" Value="DeepPink"></Setter></MultiTrigger><!--左下--><MultiTrigger><MultiTrigger.Conditions><Condition Property="HorizontalAlignment" Value="Left" ></Condition><Condition Property="VerticalAlignment" Value="Bottom" ></Condition></MultiTrigger.Conditions><Setter TargetName="brd" Property="BorderBrush" Value="Red"></Setter></MultiTrigger><!--上--><MultiTrigger><MultiTrigger.Conditions><Condition Property="HorizontalAlignment" Value="Stretch" ></Condition><Condition Property="VerticalAlignment" Value="Top" ></Condition></MultiTrigger.Conditions><Setter TargetName="brd" Property="BorderBrush" Value="Gold"></Setter></MultiTrigger><!--下--><MultiTrigger><MultiTrigger.Conditions><Condition Property="HorizontalAlignment" Value="Stretch" ></Condition><Condition Property="VerticalAlignment" Value="Bottom" ></Condition></MultiTrigger.Conditions><Setter TargetName="brd" Property="BorderBrush" Value="Indigo"></Setter></MultiTrigger><!--左--><MultiTrigger><MultiTrigger.Conditions><Condition Property="HorizontalAlignment" Value="Left" ></Condition><Condition Property="VerticalAlignment" Value="Stretch" ></Condition></MultiTrigger.Conditions><Setter TargetName="brd" Property="BorderBrush" Value="Blue"></Setter></MultiTrigger><!--右--><MultiTrigger><MultiTrigger.Conditions><Condition Property="HorizontalAlignment" Value="Right" ></Condition><Condition Property="VerticalAlignment" Value="Stretch" ></Condition></MultiTrigger.Conditions><Setter TargetName="brd" Property="BorderBrush" Value="Green"></Setter></MultiTrigger></ControlTemplate.Triggers></ControlTemplate></ac:Resize.ThumbsTemplate><TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" Text="自定义拖动点模板"></TextBlock></Grid></Grid>
</Window>

效果预览

在这里插入图片描述

5、拖动点容器模板

通过ac:Resize.ThumbsPanel设置拖动点容器模板,主要作用是设置margin,方便调整拖动点的偏移
默认的容器有Margin="-5"的偏移

(1)无Margin

此示例是为了说明无Margin的情况
xaml

<Window x:Class="WpfResize.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfResize"xmlns:ac="clr-namespace:AC"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"  WindowStyle="None"ResizeMode="NoResize"><Grid x:Name="grid" Background="White"><Grid  Margin="0,20,0,0"  ac:Resize.IsResizeable="True" ac:Resize.IsAllowsCrossover="False"  Background="SeaGreen " Height="100" Width="200" ><ac:Resize.ThumbsTemplate><ControlTemplate ><Border x:Name="brd" BorderBrush="Gray" BorderThickness="2" CornerRadius="8"  Background="White" Width="16" Height="16"/></ControlTemplate></ac:Resize.ThumbsTemplate><ac:Resize.ThumbsPanel><ItemsPanelTemplate><Grid></Grid></ItemsPanelTemplate></ac:Resize.ThumbsPanel><TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" Text="自定义拖点容器模板"></TextBlock></Grid></Grid>
</Window>

效果预览
在这里插入图片描述

(2)设置Margin

Margin设置为拖动点的一半大小就刚好在边线中间。
xaml

<Window x:Class="WpfResize.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfResize"xmlns:ac="clr-namespace:AC"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"  WindowStyle="None"ResizeMode="NoResize"><Grid x:Name="grid" Background="White"><Grid  Margin="0,20,0,0"  ac:Resize.IsResizeable="True" ac:Resize.IsAllowsCrossover="False"  Background="SeaGreen " Height="100" Width="200" ><ac:Resize.ThumbsTemplate><ControlTemplate ><Border x:Name="brd" BorderBrush="Gray" BorderThickness="2" CornerRadius="8"  Background="White" Width="16" Height="16"/></ControlTemplate></ac:Resize.ThumbsTemplate><ac:Resize.ThumbsPanel><ItemsPanelTemplate><Grid Margin="-8"></Grid></ItemsPanelTemplate></ac:Resize.ThumbsPanel><TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" Text="自定义拖点容器模板"></TextBlock></Grid></Grid>
</Window>

效果预览
在这里插入图片描述

6、整体模板

设置整体模板Template后会覆盖拖动点模板和拖动点布局模板。规则是第一级控件为容器、第二级控件为Thumb类型自动识别为拖动点,拖动方向由HorizontalAlignment和VerticalAlignment决定, 即可以有任意个拖动点Thumb,也可以放任意其他控件。

<Window x:Class="WpfResize.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfResize"xmlns:ac="clr-namespace:AC"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"  WindowStyle="None"ResizeMode="NoResize"><Grid x:Name="grid" Background="White"><Grid  Margin="0,20,0,0"  ac:Resize.IsResizeable="True"   Background="SeaGreen " Height="100" Width="200" ><ac:Resize.Template><ControlTemplate ><Grid  Margin="-4"><Grid.Resources><Style TargetType="Thumb"><Setter Property="Width" Value="8"></Setter><Setter Property="Height" Value="8"></Setter><Setter Property="Template"><Setter.Value><ControlTemplate><Border  Background="Aqua"></Border></ControlTemplate></Setter.Value></Setter></Style></Grid.Resources><Border BorderBrush="Aqua"  BorderThickness="2" Margin="4"></Border><!--左--><Thumb   HorizontalAlignment="Left"  Cursor="SizeWE"/><!--上--><Thumb   VerticalAlignment="Top" Cursor="SizeNS"/><!--右--><Thumb   HorizontalAlignment="Right"  Cursor="SizeWE"/><!--下--><Thumb    VerticalAlignment="Bottom" Cursor="SizeNS"/><!--左上--><Thumb    HorizontalAlignment="Left" VerticalAlignment="Top" Cursor="SizeNWSE"/><!--右上--><Thumb    HorizontalAlignment="Right" VerticalAlignment="Top"  Cursor="SizeNESW"/><!--右下--><Thumb    HorizontalAlignment="Right" VerticalAlignment="Bottom"  Cursor="SizeNWSE"/><!--左下--><Thumb    HorizontalAlignment="Left" VerticalAlignment="Bottom" Cursor="SizeNESW"/></Grid></ControlTemplate></ac:Resize.Template><TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" Text="自定义整体模板"></TextBlock></Grid></Grid>
</Window>

效果预览
在这里插入图片描述

7、窗口平滑拖动

窗口为透明窗口(AllowTransparency为true或者WindowChrome的GlassFrameThickness为-1),附加属性 ac:Resize.IsWindowDragSmooth设置为true即可以实现平滑拖动。
注:当前版本和装饰器不兼容,拖动时装饰器可能显示在窗口外面,谨慎使用此属性

<Window x:Class="WpfResize.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfResize"xmlns:ac="clr-namespace:AC"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"  WindowStyle="None"ResizeMode="NoResize"AllowsTransparency="True"ac:Resize.IsResizeable="True"ac:Resize.IsWindowDragSmooth="True"><Grid Background="SeaGreen "/>
</Window>

作为对比先展示非平滑拖动
注:qq录制鼠标出现了偏移
在这里插入图片描述

设置平滑拖动效果预览
注:qq录制鼠标出现了偏移
在这里插入图片描述

8、拖动事件

3个事件,拖动开始ac:Resize.DragResizeStarted、拖动变化ac:Resize.DragResizeDelta、拖动结束ac:Resize.DragResizeCompleted
xaml

<Window x:Class="WpfResize.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfResize"xmlns:ac="clr-namespace:AC"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"  ><Grid Background="SeaGreen "><Border Background="Aqua" Width="200" Height="200"   ac:Resize.IsResizeable="True"  ac:Resize.DragResizeStarted="Border_DragResizeStarted"  ac:Resize.DragResizeCompleted="Border_DragResizeCompleted" ac:Resize.DragResizeDelta="Border_DragResizeDelta"></Border></Grid>
</Window>

cs

using AC;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;namespace WpfResize
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}private void Border_DragResizeStarted(object sender, DragResizeStartedEventArgs e){Console.WriteLine("开始拖动");}private void Border_DragResizeCompleted(object sender, DragResizeCompletedEventArgs e){Console.WriteLine("结束拖动");}private void Border_DragResizeDelta(object sender, DragResizeDeltaEventArgs e){Console.WriteLine("横向变化:"+e.HorizontalChange+ " 纵向变化:"+e.VerticalChange+ " 宽变化:" + e.WidthChange + " 高变化:" + e.HeightChange);}}
}

效果预览
注:qq录制鼠标出现了偏移在这里插入图片描述

9、其他功能

(1)适应MinWidth、MinHeight

xaml

<Window x:Class="WpfResize.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfResize"xmlns:ac="clr-namespace:AC"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"  ><Grid Background="SeaGreen "><Border Background="Aqua" MinWidth="100" MinHeight="100" Width="200" Height="200"   ac:Resize.IsResizeable="True"  ></Border></Grid>
</Window>

效果预览
注:qq录制鼠标出现了偏移
在这里插入图片描述

(2)适应MaxWidth、MaxHeight

xaml

<Window x:Class="WpfResize.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:WpfResize"xmlns:ac="clr-namespace:AC"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"  ><Grid Background="SeaGreen "><Border Background="Aqua" MaxWidth="200" MaxHeight="200" Width="100" Height="100"   ac:Resize.IsResizeable="True"  ></Border></Grid>
</Window>

效果预览
在这里插入图片描述


总结

以上就是今天要讲的内容,拓展后的功能更加全面以及兼容性更强了,比如DragRezie就可以用于画板,边界限制也是比较实用的功能,拖动点模板简化了自定义的难度,拖动事件可以用于实现撤销重做功能,窗口平滑拖动优化了使用体验。但是还是有些功能不够完,需要后期继续优化。总的来说,本文实现的拖动调整大小模块已经变得更加方便实用,后期还会继续完善优化。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/625953.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Flink 处理函数(1)—— 基本处理函数

在 Flink 的多层 API中&#xff0c;处理函数是最底层的API&#xff0c;是所有转换算子的一个概括性的表达&#xff0c;可以自定义处理逻辑 在处理函数中&#xff0c;我们直面的就是数据流中最基本的元素&#xff1a;数据事件&#xff08;event&#xff09;、状态&#xff08;st…

基于SSM的项目监管系统设计与实现

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;采用JSP技术开发 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#x…

xtdrone用键盘控制无人机飞行 无法起飞

运行案例 解锁无人机螺旋桨转动但无法起飞 也未报错 解决方法&#xff1a; 在QGC中修改&#xff1a;PX4飞控EKF配置 将PX4使用的EKF配置为融合GPS的水平位置与气压计高度。 如果我们想使用视觉定位&#xff0c;就需要把修改配置文件。 此修改意味着EKF融合来自mavros/vision_…

基于SSM的网上招聘系统的设计与实现

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;Vue 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#xff1a;是 目录…

AtCoder Beginner Contest 336 G. 16 Integers(图计数 欧拉路径转欧拉回路 矩阵树定理 best定理)

题目 给16个非负整数&#xff0c;x[i∈(0,1)][j∈(0,1)][k∈(0,1)][l∈(0,1)] 求长为n3的01串的方案数&#xff0c;满足长度为4的ijkl&#xff08;2*2*2*2&#xff0c;16种情况&#xff09;串恰为x[i][j][k][l]个 答案对998244353取模 思路来源 https://www.cnblogs.com/tz…

Go后端开发 -- 数组 slice map range

Go后端开发 – 数组 && slice && map && range 文章目录 Go后端开发 -- 数组 && slice && map && range一、数组1.数组的声明和初始化2.数组的传参 二、slice切片1.slice的定义和初始化2.len()和cap()函数3.空切片4.切片截取5…

【计算机组成与体系结构Ⅱ】指令调度与分支延迟(实验)

实验4&#xff1a;指令调度与分支延迟 一、实验目的 1. 加深对指令调度技术的理解。 2. 加深对分支延迟技术的理解。 3. 熟练采用指令调度技术解决流水线中的数据冲突的方法。 4. 进一步理解指令调度技术对CPU性能的改进。 5. 进一步理解延迟分支技术对CPU性能的改进。 二…

装完32G内存条 电脑飞跃提升!

我是南城余&#xff01;阿里云开发者平台专家博士证书获得者&#xff01; 欢迎关注我的博客&#xff01;一同成长&#xff01; 一名从事运维开发的worker&#xff0c;记录分享学习。 专注于AI&#xff0c;运维开发&#xff0c;windows Linux 系统领域的分享&#xff01; 大家…

MiniTab的拟合回归模型的分析

拟合回归模型概述 使用拟合回归模型和普通最小二乘法可以描述一组预测变量和一个连续响应之间的关系。可以包括交互作用项和多项式项、执行逐步回归和变换偏斜数据。 例如&#xff0c;房地产评估人员想了解城市公寓与多个预测变量&#xff08;包括建筑面积、可用单元数量、建…

【YOLO系列】 YOLOv4之Focal Loss损失函数

论文下载&#xff1a;Focal Loss for Dense Object Detection 一、简介 Focal Loss损失函数何凯明大神在RetinaNet网络中提出来的&#xff0c;主要是为了解决one-stage目标检测中正负样本比例严重失衡的问题。该损失函数降低了大量简单负样本在训练中所占的比重&#xff0c;也可…

安装Anaconda遇到的问题

报错如下&#xff1a; Anaconda3 5.1.0(64-bit) Setup Error:Due to incompatibility with several Pyth on libraries, Destination Folder’cannot contain non-ascii characters(special characters or diacritics). Please choose another location. 原因&#xff1a;安装…

基于ssm百货中心供应链管理系统+jsp论文

摘 要 社会发展日新月异&#xff0c;用计算机应用实现数据管理功能已经算是很完善的了&#xff0c;但是随着移动互联网的到来&#xff0c;处理信息不再受制于地理位置的限制&#xff0c;处理信息及时高效&#xff0c;备受人们的喜爱。本次开发一套百货中心供应链管理系统有管理…

transfomer中Decoder和Encoder的base_layer的源码实现

简介 Encoder和Decoder共同组成transfomer,分别对应图中左右浅绿色框内的部分. Encoder&#xff1a; 目的&#xff1a;将输入的特征图转换为一系列自注意力的输出。 工作原理&#xff1a;首先&#xff0c;通过卷积神经网络&#xff08;CNN&#xff09;提取输入图像的特征。然…

构建未来教育:在线培训系统开发的技术探讨

随着远程学习的崛起和数字化教育的普及&#xff0c;在线培训系统的开发成为了现代教育的核心。本文将深入讨论在线培训系统的关键技术要点&#xff0c;涵盖前后端开发、数据库管理、以及安全性和身份验证等关键方面。 前端开发&#xff1a;提供交互性与用户友好体验 在构建在…

京东ES支持ZSTD压缩算法上线了:高性能,低成本 | 京东云技术团队

1 前言 在《ElasticSearch降本增效常见的方法》一文中曾提到过zstd压缩算法[1]&#xff0c;一步一个脚印我们终于在京东ES上线支持了zstd&#xff1b;我觉得促使目标完成主要以下几点原因&#xff1a; Elastic官方原因&#xff1a;zstd压缩算法没有在Elastic官方的开发计划中&…

最新智能AI系统ChatGPT网站程序源码+详细图文搭建部署教程,Midjourney绘画,GPT语音对话+ChatFile文档对话总结+DALL-E3文生图

一、前言 SparkAi创作系统是基于ChatGPT进行开发的Ai智能问答系统和Midjourney绘画系统&#xff0c;支持OpenAI-GPT全模型国内AI全模型。本期针对源码系统整体测试下来非常完美&#xff0c;可以说SparkAi是目前国内一款的ChatGPT对接OpenAI软件系统。那么如何搭建部署AI创作Ch…

如何增加服务器的高并发

随着互联网的快速发展和普及&#xff0c;越来越多的应用程序需要支持高并发的请求处理。在这种情况下增加服务器的高并发能力成为了一个热门的话题。下面简单的介绍如果提高服务器的高并发能力。 负载均衡 是把请求分发到多个服务器上&#xff0c;来实现请求的平衡和分担。负…

(一)环境部署

Python虚拟环境 安装virtualenv pip install virtualenv 创建环境 virtualenv -p D:\python\python.exe(python解释器目录) env-py3.6(虚拟环境目录&#xff0c;名称随意) 在当前目录下生成env-py3.6目录。 激活环境 ...\env-py3.6\Scripts> .\activate 关闭&#xf…

STM32 CubeIDE 使用 CMSIS-DAP烧录 (方法2--外部小工具)

前言&#xff1a; 本篇所用方法&#xff0c;需要借助一个外部的工具小软件。 优点&#xff1a;烧录更稳定; 缺点&#xff1a;不能在线仿真调试。 下面链接&#xff0c;是另一种方法&#xff1a;修改CubeIDE调试文件。能在CubeIDE直接烧录、仿真&#xff0c;但不稳定。…

Bazel

简介&#xff1a; Bazel 是 google 研发的一款开源构建和测试工具,也是一种简单、易读的构建工具。 Bazel 支持多种编程语言的项目&#xff0c;并针对多个平台构建输出。 高级构建语言&#xff1a;Bazel 使用一种抽象的、人类可读的语言在高语义级别上描述项目的构建属性。与其…