使用鼠标移动时的 WPF 剪切边框
本文关键字:WPF 边框 鼠标 移动 | 更新日期: 2023-09-27 18:37:02
我正在尝试让一些代码工作,允许使用鼠标移动UIElement。除非将要拖动的 UI 元素从其包含窗口的底部或右侧移动到其高度或宽度范围内,否则它会被剪裁。更改要拖动的 UIElement 的大小后,很明显,剪切区域与相对于右侧或底部的宽度或高度成正比。
<Window
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"
x:Class="MainWindow"
mc:Ignorable="d"
Title="" Height="500" Width="500" MaxWidth="500" MaxHeight="500">
<Grid>
<Border BorderBrush="Black"
MouseLeftButtonDown="UIElement_OnMouseLeftButtonDown"
MouseLeftButtonUp="UIElement_OnMouseLeftButtonUp"
MouseMove="UIElement_OnMouseMove" BorderThickness="1" Background="#FFDE1B1B"
VerticalAlignment="Top" HorizontalAlignment="Left" Width="100" Height="100"
Margin="84,82,0,0"/>
</Grid>
</Window>
public partial class MainWindow : Window
{
private bool moving = false;
Point _previous = new Point();
public MainWindow()
{
InitializeComponent();
}
private void UIElement_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var l = e.Source as UIElement;
if (l != null && l.IsMouseDirectlyOver)
{
_previous = e.GetPosition(null);
l.CaptureMouse();
moving = true;
}
}
private void UIElement_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Console.WriteLine(this.Width + ", " + this.Height);
var l = e.Source as UIElement;
if (l != null)
{
l.ReleaseMouseCapture();
moving = false;
}
}
private void UIElement_OnMouseMove(object sender, MouseEventArgs e)
{
if (moving)
{
var p = e.GetPosition(null);
if (_previous != default(Point))
{
var ui = sender as FrameworkElement;
var deltaX = p.X - _previous.X;
var deltaY = p.Y - _previous.Y;
ui.Margin = new Thickness(
Math.Max(ui.Margin.Left + deltaX, 0),
Math.Max(ui.Margin.Top + deltaY, 0),
ui.Width,
ui.Height);
Title = ui.Margin.ToString();
}
_previous = p;
}
}
}
目前不知道为什么边界被剪掉了。
因为您专门设置了要ui.Width
的右边缘的边距,以及要ui.Height
的底部边缘的边距。将它们都设置为 0(默认值),并且不会裁剪元素。
ui.Margin = new Thickness(
Math.Max(ui.Margin.Left + deltaX, 0),
Math.Max(ui.Margin.Top + deltaY, 0),
0, //ui.Width,
0); //ui.Height);