#744 – Keeping an Element within Window During Touch Manipulation
January 29, 2013 1 Comment
You can use the ManipulationDelta event handler to translate a user interface element in response to the user touching and dragging it. In the previous code, there was nothing preventing the user from sliding the element off of the screen.
We can make the element stop when it hits a window boundary by checking its bounds against the bounds of its parent. Below is the update code for the ManipulationDelta event handler that does the checking. (See earlier example for the full code sample).
private void Image_ManipulationDelta(object sender, ManipulationDeltaEventArgs e) { ManipulationDelta md = e.DeltaManipulation; Vector trans = md.Translation; Matrix m = imageTransform.Matrix; // Find center of element and then transform to get current location of center FrameworkElement fe = e.Source as FrameworkElement; Point center = new Point(fe.ActualWidth / 2, fe.ActualHeight / 2); center = m.Transform(center); // Check to see if element is at one of the edges of the window FrameworkElement feParent = fe.Parent as FrameworkElement; bool atEdge = false; if (feParent != null) { Rect feRect = fe.TransformToAncestor(feParent).TransformBounds( new Rect(0.0, 0.0, fe.ActualWidth, fe.ActualHeight)); atEdge = (feRect.Right + trans.X) > feParent.ActualWidth || (feRect.Bottom + trans.Y) > feParent.ActualHeight || (feRect.Left + trans.X) < 0 || (feRect.Top + trans.Y) < 0; } // Update matrix to reflect translation if (!atEdge) m.Translate(trans.X, trans.Y); imageTransform.Matrix = m; RaisePropertyChanged("ImageTransform"); e.Handled = true; }
Pingback: Dew Drop – January 29, 2013 (#1,489) | Alvin Ashcraft's Morning Dew