Page 1 of 1

Drawing in WPF(C#)

#1 RexGrammer   User is offline

  • Coding Dynamo
  • member icon

Reputation: 183
  • View blog
  • Posts: 785
  • Joined: 27-October 11

Posted 06 January 2012 - 07:08 AM

Drawing in WPF

I'll try to explain drawing in WPF while comparing it to drawing in WinForms

This tutorial should introduce you to drawing in WPF. It's recommended to know how to draw in WinForms before reading this tutorial, but it's not required (since drawing in WPF has little to do with drawing in WinForms). Following the same analogy as many functionalities in WPF this concept is based on nesting elements one in another.

WPF comes with a class called 'Line' and one called 'Canvas'. We will use these in our example but you can use any other shape (in WPF that's a class that inherits from Shape Class)

More info on the:

Line Class
Canvas Class

So first create a WPF application (I trust you know how to do this... :D)

1. Add a canvas control to the main window
2. Rename it to drawingCanvas
3. Add a button control to the main window
4. Rename it to testButton
5. Create an event handler for the testButton_Click event (Just double click the button in the designer)

In WPF you need to create a Line object and add it to a control (In our case the Canvas control). But before we add it to the control we need to define some properties of our line (Like the position and the Stroke).

Drawing the line through code
Create a new Line object:
Line myLine = new Line();

Define it's start and end point coordinates:
myLine.X1 = 10;
myLine.Y1 = 10;
myLine.X2 = 50;
myLine.Y1 = 50;

After that we need to define the stroke property. It is a Brush Class that is actually the outline of the shape.

You can define the stroke property like this:
myLine.Stroke = new SolidColorBrush(Color.FromArgb(100, 50, 125, 255));

NOTE: I didn't create a local variable to hold the brush.

Now we need to add that line object to the canvas control:

Build and start the application. Click the button. Voila! :D

Drawing the line through XAML

It's the same process:
1. Define the properties of the line
2. Nest it in the canvas control

So it's easy:

Open the <Line XAML tag, define the point coordinates (X1="10" Y1="10" X2="50" Y2="50", you can chose different points), define the stroke property (Stroke="Black", chose a different color if you want), close the tag />.

The complete line looks like this:
<Line X1="10" Y1="10" X2="50" Y2="50" Stroke="Black"/>

Build and start the application. Click the button. Voila! :D
You can apply the same logic for the Ellipse Class or any other shape for that matter. Of course the same logic applies for all shapes.

Hope this gets you started drawing in WPF! :D

Is This A Good Question/Topic? 0
  • +

Page 1 of 1