MasterMastic
MasterMastic

Reputation: 21286

Drawing to a brush

I have made a control which inherits TextBox, and I'm trying to give a notebook grid:

Notebook page

I already have the code that will specify where to draw the lines including all of the grids features, but I'm not sure what to draw it to. I've Googled a lot and searched for a brush that will let me have the same interface as a DrawingContext (so I could call drawingContext.DrawLine() etc.), or something familiar, but I couldn't find any!

So how can I achieve to get my grid background?

P.S I can't create a static bmp file and load it, because the grid color and spacing would most certainly change

Upvotes: 1

Views: 727

Answers (3)

Mark Hall
Mark Hall

Reputation: 54522

You could try using DrawingVisual to get your DrawingContext then create a VisualBrush to assign to your Background. Something like this.

DrawingVisual dv = new DrawingVisual();
DrawingContext dc = dv.RenderOpen();

dc.DrawLine( new Pen(Brushes.Red,5),new Point(0,0),new Point(50,50));
dc.Close();

VisualBrush vb = new VisualBrush(dv);
textBox1.Background = vb;

Upvotes: 1

solud
solud

Reputation: 56

You're looking to make a custom-drawn control. You'll want to override the OnPaint method of your control class and draw the background in that method. Here's an example on how to do it: http://msdn.microsoft.com/en-us/library/b818z6z6(v=vs.90).aspx

To draw your background, grab the drawing context and draw your background after first calling the base OnPaint method:

protected override void OnPaint(PaintEventArgs pe)
{
   // Call the OnPaint method of the base class.
   base.OnPaint(pe);

   // Declare and instantiate a new pen.
   System.Drawing.Pen myPen = new System.Drawing.Pen(Color.Aqua);

   // Draw an aqua rectangle in the rectangle represented by the control.
   pe.Graphics.DrawRectangle(myPen, new Rectangle(this.Location, this.Size));
}

EDIT: Since you're using WPF, you can take a look here to see a full example on custom designs: WPF .NET 3.5 Drawing Customized Controls and Custom UI Elements

Upvotes: 0

João Mendes
João Mendes

Reputation: 1425

You can intercept the Paint event for your control. You get a PaintEventArgs argument, which includes a ClipRectangle and a Graphics object.

Check out Control.Paint Event.

Once you have your Graphics object, you can call DrawLine and FillRectangle on it directly.

Upvotes: 0

Related Questions