Search code examples
silverlightsilverlight-4.0designersilverlight-toolkit

Silverlight snapping to grid


I am in the process of creating a visual designer for which i need the snap to grid functionality like the one provided by mocking Bird ( Demo ). Is there any project, usercontrol or resources that will help me develop the same in silverlight as quick as possible.

I have been able to accomplish the drag and drop operation from the toolbox (Listbox ) to the canvas at the center of the designer screen. But the snap to grid and grid functionality is superb to have in the designer.


Solution

  • In your MouseMove routine, you need to do an additional adjustment to allow for snapping.

    void MainImage_MouseMove(object sender, MouseMoveEventArgs args){
    
        // ... assume you have calculated newX and newY already
    
        adjustSnap(ref newX, ref newY);
    
        // ... position your element
    
    }
    
    bool _isSnapOn = true;
    
    void adjustSnap(ref double x, ref double y)
    {
        const double gridWidth = 100;
        const double gridHeight = 100;
    
        if (_isSnapOn) 
        {
    
            if (x % gridWidth < gridWidth/2)
                x -= x % gridWidth;
            else
                x += (gridWidth - x % gridWidth);
    
            if (y % gridHeight < gridHeight / 2)
                y -= y % gridHeight;
            else
                y += (gridHeight - y % gridHeight);
        }
    }