title: Implementing WPF Snap Grid
body: <p>I am trying to implement a snap grid using WPF and a canvas.  I am thinking my math is off because the UIElement won't snap to the grid in the background.  Below is the xaml I use to create the grid and the method I use to try and snap the UIElement to the closest grid line.  The method used is fired as soon as the mouse button up event is fired.  If this not the correct approach for WPF can someone point me in the right direction?</p>
  
  <p>XAML</p>
  
  <pre><code> &lt;Border x:Name="dragBorder" 
              BorderBrush="Black"
              BorderThickness="1"
              Margin="5"
              CornerRadius="3"&gt;
          &lt;Canvas x:Name="dragCanvas"
                              AllowDragging="true"
                              AllowDragOutOfView="False"
                              Height="{Binding ElementName=dragBorder, Path=ActualHeight}"
                              Width="{Binding ElementName=dragBorder, Path=ActualWidth}"&gt;
              &lt;Canvas.Background&gt;
                  &lt;VisualBrush TileMode="Tile"
                               Viewport="0,0,16,16"
                               ViewportUnits="Absolute"
                               Viewbox="0,0,16,16"
                               ViewboxUnits="Absolute"&gt;
                      &lt;VisualBrush.Visual&gt;
                          &lt;Ellipse Fill="#FF000000"
                                   Width="2"
                                   Height="2" /&gt;
                      &lt;/VisualBrush.Visual&gt;
                  &lt;/VisualBrush&gt;
              &lt;/Canvas.Background&gt;
          &lt;/Canvas&gt;
      &lt;/Border&gt;
  </code></pre>
  
  <p>Method</p>
  
  <pre><code>private void SnapToGrid(UIElement element)
      {
          double xSnap = (Canvas.GetLeft(element) / gridWidth) * gridWidth;
          double ySnap = (Canvas.GetTop(element) / gridWidth) * gridWidth;
  
          Canvas.SetLeft(element, xSnap);
          Canvas.SetTop(element, ySnap);
  
          double tempX = Canvas.GetLeft(element);
          double tempY = Canvas.GetTop(element);
      }   
  </code></pre>