Search code examples
c#wpfbackgroundgridvisualbrush

Draw a snap pattern on a Grid control


I have a solution that I use but that one is not really giving me all the abilities that I need.

Right now, I'm setting the background of my Grid control to a VisualBrush that contains an ellipse on its Visual container. This makes it impossible for me to set a background color(or at least with my knowledge until now) BEHIND the drawn squares.

I am using these squares as markers for my snap to position functionality. See pic.

https://i.sstatic.net/J9CZf.jpg

Is there a possible way for me to keep my background pattern and also be able to set a background color? Another approach are also welcome as I feel like I have snowed in on this one because it works(partially).

Due to demand:

  brush = new VisualBrush();
  brush.Stretch = Stretch.Fill;
  brush.TileMode = TileMode.Tile;
  brush.Viewport = new Rect(0, 0, SnapDistance, SnapDistance);
  brush.ViewportUnits = BrushMappingMode.Absolute;
  brush.Viewbox = new Rect(0, 0, SnapDistance, SnapDistance);
  brush.ViewboxUnits = BrushMappingMode.Absolute;
  ellipse = new Ellipse() { Fill = new SolidColorBrush(Colors.Blue), Width = 2, Height = 2 };
  brush.Visual = ellipse;

This is what I set to the grid.Background. What I want to do is to draw the pattern I show in the link and also be able to set a color to the background with the dot pattern on that.


Solution

  • You can overlay the grid with Canvas with the snap points or you can create an adorner layer with the snap points.

    Cite from MSDN page

    Adorners are a special type of FrameworkElement, used to provide visual cues to a user. Among other uses, Adorners can be used to add functional handles to elements or provide state information about a control.

    So the controls layout (in Z-order) will be:

    • the grid
    • the overlay with the snap points (don't know how the events will be handled then)
    • your elements

    or

    • the grid
      • the adorner layer
    • your elements