[英]WPF clipping border when moving with mouse
我試圖使一些代碼可以使用鼠標移動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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.