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?
XAML
<Border x:Name="dragBorder"
BorderBrush="Black"
BorderThickness="1"
Margin="5"
CornerRadius="3">
<Canvas x:Name="dragCanvas"
AllowDragging="true"
AllowDragOutOfView="False"
Height="{Binding ElementName=dragBorder, Path=ActualHeight}"
Width="{Binding ElementName=dragBorder, Path=ActualWidth}">
<Canvas.Background>
<VisualBrush TileMode="Tile"
Viewport="0,0,16,16"
ViewportUnits="Absolute"
Viewbox="0,0,16,16"
ViewboxUnits="Absolute">
<VisualBrush.Visual>
<Ellipse Fill="#FF000000"
Width="2"
Height="2" />
</VisualBrush.Visual>
</VisualBrush>
</Canvas.Background>
</Canvas>
</Border>
Method
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);
}