So I have a Border with a TranslateTransform so that I can move it around my window. Within the contents of the Border I have a number of controls plus a ScrollViewer. The dragging works fine but when I click the scrollbar the whole border jumps so that my cursor is now over the last point at which I clicked. Very annoying and I can’t see why it’s happening to my scrollbar but not my other controls.
(I’m using Denis Morozov’s simple, excellent guide http://denismorozov.blogspot.ie/2008/01/drag-controls-in-wpf-using.html)
Here’s what I’m doing in code;
private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
this.current.X = Mouse.GetPosition((IInputElement)sender).X;
this.current.Y = Mouse.GetPosition((IInputElement)sender).Y;
// Ensure object receives all mouse events.
this.current.InputElement.CaptureMouse();
}
private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
if (this.current.InputElement != null)
this.current.InputElement.ReleaseMouseCapture();
}
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
// if mouse is down when its moving, then it's dragging current
if (e.LeftButton == MouseButtonState.Pressed)
this.current.IsDragging = true;
else
this.current.IsDragging = false;
if (this.current.IsDragging && current.InputElement != null)
{
// Retrieve the current position of the mouse.
double newX = Mouse.GetPosition((IInputElement)sender).X;
double newY = Mouse.GetPosition((IInputElement)sender).Y;
// Reset the location of the object (add to sender's renderTransform
// newPosition minus currentElement's position
Transform rt = ((UIElement)this.current.InputElement).RenderTransform;
double offsetX = rt.Value.OffsetX;
double offsetY = rt.Value.OffsetY;
rt.SetValue(TranslateTransform.XProperty, offsetX + newX - current.X);
rt.SetValue(TranslateTransform.YProperty, offsetY + newY - current.Y);
// Update position of the mouse
current.X = newX;
current.Y = newY;
}
}
public void MouseLeftBtnDown(object sender, MouseButtonEventArgs e)
{
this.current.InputElement = (IInputElement)sender;
}
Found it actually in the comments on Denis’ page. Problem lay in not resetting things on
Canvas_MouseUp. That method should actually be;Now works like a charm 😉