WPF: 旋转Thumb后,DragDelta移动距离出错的解决

时间:2022-03-30 16:46:20

当Thumb跟随Grid旋转90度后,拖拽控件时会飞掉。

<Grid x:Name="gridMain" Width="100" Height="50" Background="Green" RenderTransformOrigin="0.5,0.5" Canvas.Left="100" Canvas.Top="100">
<Grid.RenderTransform>
<RotateTransform x:Name="rotate" Angle="90"></RotateTransform>
</Grid.RenderTransform>
<Thumb x:Name="thumbMain" Opacity="0.8" DragDelta="Thumb_DragDelta"></Thumb>
</Grid>
private void Thumb_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
{
Canvas.SetLeft(gridMain, Canvas.GetLeft(gridMain) + e.HorizontalChange);
Canvas.SetTop(gridMain, Canvas.GetTop(gridMain) + e.VerticalChange);
}

 

 

这是由于坐标系不统一造成的。Canvas.SeltLeft 和 Canvas.SetTop是用的Canvas坐标系。而Thumb的e.HorizontalChange 和 e.VerticalChange 是根据鼠标相对于Thumb自身坐标系计算出来的, 两个坐标系有个90度的角度差。将e.HorizontalChange 和 e.VerticalChange转换到Canvas的坐标系下,拖拽就没问题了。如下:

private void Thumb_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
{
Point ptChange = rotate.Transform(new Point(e.HorizontalChange, e.VerticalChange));
Canvas.SetLeft(gridMain, Canvas.GetLeft(gridMain) + ptChange.X);
Canvas.SetTop(gridMain, Canvas.GetTop(gridMain) + ptChange.Y);
}