我有一个拖动图像,它位于ContentPanel中。在MouseLeave事件中,我得到图像的位置,然后我需要将它与我的网格对齐。试图用Canvas做,但没有任何反应。当我尝试改变边距时,位置是完全错误的。
代码:
private void MouseLeave(object sender, MouseEventArgs e)
{
Image rs = (Image)sender;
GeneralTransform gt = rs.TransformToVisual(ContentPanel);
Point offset = gt.Transform(new Point(0, 0));
double controlTop = offset.Y;
double controlLeft = offset.X;
tb.Text = Convert.ToInt16(controlLeft / 40).ToString();
tb2.Text = Convert.ToInt16(controlTop / 40).ToString();
double newLeft = Convert.ToInt16(controlLeft / 40)*40;
double newTop = Convert.ToInt16(controlTop / 40)*40;
//rs.Margin = new Thickness(newLeft, newTop, 0, 0);
//((Image)ContentPanel.Children[11]).SetValue(Canvas.LeftProperty, newLeft);
//((Image)ContentPanel.Children[11]).SetValue(Canvas.TopProperty, newTop);
}
那么如何设置图像的位置?
答案 0 :(得分:0)
一种方法是将转化转换应用于您的图像?
这样的事情应该有效:
Image rs = (Image)sender;
GeneralTransform gt = rs.TransformToVisual(ContentPanel);
Point offset = gt.Transform(new Point(0, 0));
//create a translate transform
TranslateTransform tt = new TranslateTransform();
//apply the required offset
tt.X = offset.X;
tt.Y = offset.Y;
//apply the transform to the image
rs.RenderTransform = tt;
double controlTop = offset.Y;
double controlLeft = offset.X;
tb.Text = Convert.ToInt16(controlLeft / 40).ToString();
tb2.Text = Convert.ToInt16(controlTop / 40).ToString();
double newLeft = Convert.ToInt16(controlLeft / 40) * 40;
double newTop = Convert.ToInt16(controlTop / 40) * 40;