Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw on a Window in WPF (best practice)?

I am trying to write a small interactive game-like application, where I need to have a Draw method that's gonna draw on screen, but can't figure out how to structure the method for WPF.

If this was Winforms, I could use:

public void Draw (Graphics g) {  } 

But for a WPF Window, what should I have on it in the xaml (currently only have a Grid), and what should this Draw method receive as an argument?

First I want to do it like this to get it working, then I can think about how to make it more WPF, etc. But now I am more interested in getting this to work.

like image 900
Joan Venge Avatar asked Apr 07 '11 18:04

Joan Venge


People also ask

How do you draw a line in WPF?

To draw a line, create a Line element. Use its X1 and Y1 properties to set its start point; and use its X2 and Y2 properties to set its end point. Finally, set its Stroke and StrokeThickness because a line without a stroke is invisible. Setting the Fill element for a line has no effect, because a line has no interior.

How do I display a WPF window?

When a Window is created at run-time using the Window object, it is not visible by default. To make it visible, we can use Show or ShowDialog method. Show method of Window class is responsible for displaying a window.

How do you draw a square in WPF?

To draw a rectangle, create a Rectangle element and specify its Width and Height. To paint the inside of the rectangle, set its Fill. To give the rectangle an outline, use its Stroke and StrokeThickness properties. To give the rectangle rounded corners, specify the optional RadiusX and RadiusY properties.

Why is WPF so difficult?

The difficulty with learning WPF is not so much the API as the model. It's a very different mental model than you'd use with something like Windows Forms. Rather than writing methods that imperatively populate a UI element, you generally data bind to properties on an object.


1 Answers

Typically, you "draw" in WPF in a completely different manner.

In Windows Forms/GDI, the graphics API is an immediate mode graphics API. Each time the window is refreshed/invalidated, you explicitly draw the contents using Graphics.

In WPF, however, things work differently. You rarely ever directly draw - instead, it's a retained mode graphics API. You tell WPF where you want the objects, and it takes care of the drawing for you.

The best way to think of it is, in Windows Forms, you'd say "Draw a line from X1 to Y1. Then draw a line from X2 to Y2. Then ...". And you repeat this every time you need to "redraw" since the screen is invalidated.

In WPF, instead, you say "I want a line from X1 to Y1. I want a line from X2 to Y2." WPF then decides when and how to draw it for you.

This is done by placing the shapes on a Canvas, and then letting WPF do all of the hard work.

like image 60
Reed Copsey Avatar answered Sep 26 '22 03:09

Reed Copsey