Creating a Canvas Background Dynamically

1.7k Views Asked by At

I currently have a canvas which contains a bunch of sqaures as its children. These sqaures sit on different lines. I would like to draw a background for the canvas which draws lines (like a notepad would have feint blue lines on the paper) I would like to draw this dynamically by binding it to a collection of "lines" So if there are 2 lines in the collection, 2 lines will be drawn on the background of the canvas. I was looking into using DrawingBrush, but i am not sure if this is the correct way forward

<DrawingBrush>
  <DrawingBrush.Drawing>
    <Line Name=Line1/>
    <Line Name=Line2/>
  </DrawingBrush.Drawing>
</DrawingBrush>

(BTW The above code does not work, it is just to explain the conecpt)

2

There are 2 best solutions below

6
On BEST ANSWER

Try this approach. Use a new class for your canvas:

internal class SpecialCanvas : Canvas
{
    ...

    ObservableCollection<Line> Lines {get; set;}

    DrawingVisual backgroundVisual = new DrawingVisual;

    public SpecialCanvas()
    {
        this.Background = new VisualBrush(backgroundVisual);   
    }

    private void OnLinesChanged(...)
    {
       using (DrawingContext dc = this.backgroundVisual.RenderOpen())
       {
           // Draw your lines to dc here.
       }
    }

}

0
On

There are a lot of ways you could possibly do what you want to do. For a simple XAML only solution, you could just use an itemscontrol.

<Window.Resources>
    <x:Array x:Key="Lines" Type="{x:Type Line}"> 
        <Line X1="0" X2="400" Y1="25" Y2="25" Stroke="Black" />
        <Line X1="0" X2="400" Y1="25" Y2="25" Stroke="Black" />
    </x:Array>

</Window.Resources>
<Canvas>
    <ItemsControl ItemsSource="{StaticResource Lines}" />

    <Rectangle Height="20" Width="20" Canvas.Left="20" Canvas.Top="5" Stroke="Blue" Fill="Blue" />
    <Rectangle Height="20" Width="20" Canvas.Left="120" Canvas.Top="5" Stroke="Blue" Fill="Blue" />
    <Rectangle Height="20" Width="20" Canvas.Left="20" Canvas.Top="30" Stroke="Blue" Fill="Blue" />
    <Rectangle Height="20" Width="20" Canvas.Left="120" Canvas.Top="30" Stroke="Blue" Fill="Blue" />
</Canvas>