gpt4 book ai didi

c# - 拖动用户控件,但将其保留在 WPF 中其父级的范围内

转载 作者:太空狗 更新时间:2023-10-29 23:37:11 26 4
gpt4 key购买 nike

我有一个用户控件,我正在将其拖到网格内。 Z-Index 设置得相当高,这样我就可以将它保持在其他 child 之上。拖动控件效果很好,但如果用户想将控件移到网格之外,它会允许。

enter image description here我如何防止它离开父网格控件的边界,这是我现在拥有的:

   private System.Windows.Point _anchorPoint;
private System.Windows.Point _currentPoint;
private bool _isInDrag;

private void UserControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var element = sender as FrameworkElement;
_anchorPoint = e.GetPosition(null);
if (element != null) element.CaptureMouse();
_isInDrag = true;
e.Handled = true;
}

private void UserControl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (!_isInDrag) return;
var element = sender as FrameworkElement;
if (element != null) element.ReleaseMouseCapture();
_isInDrag = false;
e.Handled = true;
}

private void UserControl_MouseMove(object sender, MouseEventArgs e)
{
if (!_isInDrag) return;
_currentPoint = e.GetPosition(null);

UIElement container = VisualTreeHelper.GetParent(_parentGrid) as UIElement;
System.Windows.Point relativeLocation = _parentGrid.TranslatePoint(new System.Windows.Point(0, 0), container);

if (_currentPoint.X > relativeLocation.X) return;
if(_currentPoint.Y >= relativeLocation.Y)return;

_transform.X += _currentPoint.X - _anchorPoint.X;
_transform.Y += (_currentPoint.Y - _anchorPoint.Y);
RenderTransform = _transform;
_anchorPoint = _currentPoint;
}

“relativeLocation”始终为 0x0,因此无法正常工作。任何想法将不胜感激。

*注意:我知道如果我将 UserControl 更改为 Window,它会减轻我遇到的所有问题。但老实说,这样看起来很棒,我真的不想把 window 弄得乱七八糟。该系统作为仪表板打开,占据用户的整个窗口(在单独的窗口中打开)。所以当你在这里打开一个窗口时,它不会正确流动。

最佳答案

我认为您不需要 relativeLocation。不过,数学可能有点烦人。试试这个方法,我测试的时候效果很好:

    private void UserControl_MouseMove(object sender, MouseEventArgs e)
{
if (!_isInDrag) return;
_currentPoint = e.GetPosition(null);

//This is the change to the position that we want to apply
Point delta = new Point();
delta.X = _currentPoint.X - _anchorPoint.X;
delta.Y = _currentPoint.Y - _anchorPoint.Y;

//Calculate user control edges
var leftEdge = Margin.Left + _transform.X + delta.X;
var topEdge = Margin.Top + _transform.Y + delta.Y;
var rightEdge = Width + Margin.Left + _transform.X + delta.X;
var bottomEdge = Height + Margin.Top + _transform.Y + delta.Y;

//Set the delta to 0 if it goes over _parentGrid edges
if (leftEdge < 0) delta.X = 0;
if (topEdge < 0) delta.Y = 0;

if (rightEdge > _parentGrid.Width) delta.X = 0;
if (bottomEdge > _parentGrid.Height) delta.Y = 0;

//Apply the delta to the user control
_transform.X += delta.X;
_transform.Y += delta.Y;
RenderTransform = _transform;
_anchorPoint = _currentPoint;
}

关于c# - 拖动用户控件,但将其保留在 WPF 中其父级的范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38132836/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com