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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With