I've been trying to translate a grid (2 arrays of lines) in a canvas via TranslateTransform. However, the lines kind of just shake about and return to their original place and do not translate. Here's the source:
private Point mousePosition;
private bool CanvasMouseDown;
private void GraphMouseDown(object sender, MouseButtonEventArgs e)
{
CanvasMouseDown = true;
}
private void GraphMouseMove(object sender, MouseEventArgs e)
{
if (CanvasMouseDown)
{
var position = e.GetPosition(canvas);
var offset = position - mousePosition;
mousePosition = position;
for (int i = 0; i < GridLinesHoriz.Length; ++i)
{
GridLinesHoriz[i].RenderTransform = new TranslateTransform(offset.X, offset.Y);
}
for (int i = 0; i < GridLinesVert.Length; ++i)
{
GridLinesVert[i].RenderTransform = new TranslateTransform(offset.X, offset.Y);
}
}
}
private void GraphMouseUp(object sender, MouseButtonEventArgs e)
{
CanvasMouseDown = false;
}
Any Help?
The problem is you are normalizing the offset as you are handling the
MouseMove
events. TheTranslateTransform
always translates from the original location, so you need to compute a running offset that's maintained for the lifetime of the drag operation.If you change
mousePosition
to class level variable and set that variable when the operation starts (in theMouseDown
event handler) and stop updating that variable in theMouseMove
event handler, the lines will start translating the way you expect.