Tag Archives: Geometry

Using GeometryPath XAML as a Path.Data template in Silverlight

In this post I’m going to discuss how to use a GeometryPath as a template for building several Path controls.

Let’s assume we have to build a Silverlight application that is able to draw Circles and Rectangles on a canvas

On a very simple level, one possible approach would be the following:

  • build basic UI on the main window (controls for selecting the shape type and a canvas)
  • handle mouse click on the canvas
  • on each mouse click build a shape according to selected shape type  and placed it on the current mouse position

One idea could be to just create Circles and Rectangles as the user clicks the canvas and with a few lines of code the resulting application looks pretty well.

The problem with this approach is that it is hard to add complex shapes.

Adding even a simple Star would be a rather complicated job: imagine having to add the 10 line segments after calculating the coordinates… it can really take a while. And if you think that a star is not too complicated, think of a more complex shape: a lightning, a cloud, etc.

I will now present you with an alternative that might save you some time.

As the main challenge is to build complex shapes, let’s pass that task to a specialized tool, namely Microsoft Expression Design 4.

Expression Design can be used to draw various shapes and it can export them in XAML format.

We’ll convert all our shapes to Paths and we will use the XAML specific Data to create our shapes.

The advantage is that once we have the Data representation, we can use this CodePlex project http://stringtopathgeometry.codeplex.com/ that can transform it into a PathGeometry.

The code might not look very clean because of the raw data of the path, but it saves us a lot of work and it makes our life easier in the future.

Basically for adding new shapes we now only need to:

  • draw the shape in Expression Design
  • export the shape and use its Data string to populate the appropriate templates dictionary entry in the ShapeFactory class

It is that simple!

Add some transformation, coloring and better UI and you have a nice drawing tool in Silverlight.

Download Source code here (VS2010 Silverlight 4 project)