gpt4 book ai didi

.net - MouseEventArgs.GetPosition 在 WPF 中没有按预期工作

转载 作者:行者123 更新时间:2023-12-05 06:45:58 32 4
gpt4 key购买 nike

我会尝试一点 Shapemoving 并编写以下应用程序:

<Window x:Class="WpfApplication7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="27" />
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ToolBar Grid.Row="0"/>
<Canvas Grid.Row="1" MouseDown="OnMouseDown" MouseUp="OnMouseUp" MouseMove="OnMouseMove">
<Ellipse Width="100" Height="100" Fill="Red" Canvas.Left="50" Canvas.Top="50" />
<Ellipse Width="100" Height="100" Fill="Red" Canvas.Left="180" Canvas.Top="50" />
<Rectangle Width="100" Height="100" Fill="Blue" Canvas.Left="220" Canvas.Top="160" />
</Canvas>
</Grid>
</Window>

和背后的代码:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace WpfApplication7
{
public partial class MainWindow
{
private UIElement SelectedObject { get; set; }
private bool captureMouse;
private Point diffPosition;

public MainWindow()
{
InitializeComponent();
}

private void OnMouseDown(object sender, MouseButtonEventArgs e)
{
SelectedObject = e.Source as UIElement;
if (SelectedObject != null)
{
captureMouse = SelectedObject.CaptureMouse();
diffPosition = e.GetPosition(SelectedObject);
}
}

private void OnMouseUp(object sender, MouseButtonEventArgs e)
{
if (captureMouse)
{
SelectedObject.ReleaseMouseCapture();
}
SelectedObject = null;
}

private void OnMouseMove(object sender, MouseEventArgs e)
{
if (SelectedObject != null)
{
Canvas.SetLeft(SelectedObject, e.GetPosition(this).X - diffPosition.X);
Canvas.SetTop(SelectedObject, e.GetPosition(this).Y - diffPosition.Y);
}
}
}
}

我想在 OnMouseDown 中使用 GetPosition 相对于 SelectedObject 获取点击点的 diffPosition 拯救我几行代码,但增加了工具栏的高度。所以我的 Y 坐标比我预期的多 27 个像素。如果我删除工具栏,一切正常。我需要做什么才能使表单中的工具栏获得正确的偏移量?

我知道这只是一个小错误,但我找不到。

最佳答案

命名您的绘图区域:

 <Canvas Grid.Row="1" x:Name="drawingArea" ...>
...
</Canvas>

并将位置与 drawingArea 的进行比较。

e.GetPosition(this.drawingArea)

这样你就不用担心布局变化等问题

关于.net - MouseEventArgs.GetPosition 在 WPF 中没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20098435/

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