[英]Moving a Control on a Canvas on Drag & Drop
I have placed text blocks on a canvas. 我已经在画布上放置了文本块。 I change their position on mouse drag using the following code:
我使用以下代码更改它们在鼠标拖动时的位置:
protected bool isDragging;
private Point clickPosition;
private void txt_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
isDragging = true;
var draggableControl = sender as TextBlock;
clickPosition = e.GetPosition(this);
draggableControl.CaptureMouse();
}
private void txt_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
isDragging = false;
var draggable = sender as TextBlock;
draggable.ReleaseMouseCapture();
}
private void txt_MouseMove(object sender, MouseEventArgs e)
{
var draggableControl = sender as TextBlock;
if (isDragging && draggableControl != null)
{
Point currentPosition = e.GetPosition(this.Parent as UIElement);
var transform = draggableControl.RenderTransform as TranslateTransform;
if (transform == null)
{
transform = new TranslateTransform();
draggableControl.RenderTransform = transform;
}
transform.X = currentPosition.X - clickPosition.X;
transform.Y = currentPosition.Y - clickPosition.Y;
}
}
What I want here is to get the new position of the textblock, save it and next time when the application loads, the control should take the new position. 我在这里想要的是获取文本块的新位置,保存它,并在下次加载应用程序时,控件应采用新位置。 I understand that my code does not change the Left & Top property of the textblock, but instead transforms it.
我知道我的代码不会更改文本块的Left&Top属性,而是对其进行转换。 Hence, the Left and Top Property won't be changed.
因此,Left和Top属性将不会更改。 I tried to set Left and Top Property as
我试图将Left和Top Property设置为
draggableControl.SetValue(Canvas.LeftProperty, transform.X);
draggableControl.SetValue(Canvas.TopProperty, transform.Y);
But it also does not change it. 但这也不会改变。
What can be done to achieve the desired? 怎样才能达到期望?
You must not use Transform...but only 您不得使用Transform ...,而只能使用
draggableControl.SetValue(Canvas.LeftProperty, X);
draggableControl.SetValue(Canvas.TopProperty, Y);
because transform affect only rendering 因为变换只影响渲染
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.