title: Drag User Control, but keep it inside the bounds of its parent in WPF
body: <p>I have a user control that I am dragging inside of a grid. The Z-Index is set pretty high so that I can keep it above the other children. Dragging the control works perfectly, but if a user wants to move the control outside of the grid it will allow it. </p>
  
  <p><a href="https://i.stack.imgur.com/KzUdY.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/KzUdY.jpg" alt="enter image description here"></a>
  How do I keep it from leaving the bounds of the parent Grid control, here is what I have now:</p>
  
  <pre><code>   private System.Windows.Point _anchorPoint;
      private System.Windows.Point _currentPoint;
      private bool _isInDrag;
  
     private void UserControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
      {
          var element = sender as FrameworkElement;
          _anchorPoint = e.GetPosition(null);
          if (element != null) element.CaptureMouse();
          _isInDrag = true;
          e.Handled = true;
      }
  
      private void UserControl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
      {
          if (!_isInDrag) return;
          var element = sender as FrameworkElement;
          if (element != null) element.ReleaseMouseCapture();
          _isInDrag = false;
          e.Handled = true;
      }
  
     private void UserControl_MouseMove(object sender, MouseEventArgs e)
          {
              if (!_isInDrag) return;
              _currentPoint = e.GetPosition(null);
  
              UIElement container = VisualTreeHelper.GetParent(_parentGrid) as UIElement;
              System.Windows.Point relativeLocation = _parentGrid.TranslatePoint(new System.Windows.Point(0, 0), container);
  
              if (_currentPoint.X &gt; relativeLocation.X) return;
              if(_currentPoint.Y &gt;= relativeLocation.Y)return;
  
              _transform.X += _currentPoint.X - _anchorPoint.X;
              _transform.Y += (_currentPoint.Y - _anchorPoint.Y);
              RenderTransform = _transform;
              _anchorPoint = _currentPoint;
          }
  </code></pre>
  
  <p>The "relativeLocation" is always 0x0, so thats not working. Any ideas would greatly be appreciated. </p>
  
  <p>*Note : I know if I changed my UserControl to a Window it would mitigate all of the issues that I am having. But to be honest, it looks great this way and I really don't want to clutter the window up. This system opens up as a dashboard that consumes the user's' entire window ( is opened on a separate window). So when you open a window here, its doesn't flow right.</p>