我会尝试一点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);
}
}
}
}
我认为diffPosition
中的点击点OnMouseDown
与GetPosition
SelectedObject
相对于{{1}}保存了几行代码,但工具栏的高度被添加。所以我的Y坐标比我预期的多27个像素。如果我删除工具栏,一切正常。
我需要做什么才能通过表单中的工具栏获得正确的偏移量?
我知道这只是一个小错误,但我找不到它。
答案 0 :(得分:1)
命名您的绘图区域:
<Canvas Grid.Row="1" x:Name="drawingArea" ...>
...
</Canvas>
并与drawingArea的比较位置。
e.GetPosition(this.drawingArea)
这样您就不必担心布局更改等。