How to draw a shape after a mouse click?

Feb 10, 2011 at 11:55 AM

Hello all,

I have a UserControl on which I'd like to draw some shapes (basically some circles) at the location where the user clicked on it.

What is the best way to do that using CM?

Thanks in advance


Feb 10, 2011 at 2:08 PM

You have many options, depending on the requirements and the kind of drawind you would like to obtain.
Assuming you just have to track a moderate amount of shapes (sort of vector graphic drawing), you might consider representing the drawings with some view models (tracking propert), then display them in the view side using shape elements bound to the view model properties.

This approach has the advantage of letting you to manage the drawing (and eventuall its persistence) entirely in the VM side.

Does it make sense for your scenario?

Feb 10, 2011 at 2:19 PM

This is the kind of answer I had thought about, and I'm happy you mention it.

I was thinking to a shape VM like:

public class DotShapeViewModel : Screen
    public double X { get; set };
    public double Y { get; set };
    public Color BackGround { get; set; }

I can manage an observable collection of DotShapeViewModel. But how can I draw the dots in the view, at the correct coordinates?

Thanks in advance

Feb 10, 2011 at 2:30 PM
Edited Feb 10, 2011 at 2:31 PM

It depends on the UI elements used to represent the data.

You could use a Canvas to layout your dots. In such a case dots could be represented by Rectangles whose Canvas.Left/Canvas.Top properties are bound to the view-model X/Y coordinates.

Another possible approach is to use a Grid with shapes presented as customized Shape (you need a StreamGeometry in this case)

You could event define views as a Path and use a MultiBinding over the coordinates to determine the geometry.

There are a lot of ways to draw shapes (even the InkCanvas).

Feb 10, 2011 at 3:03 PM

Thanks for your explanations.

I'll dig a little to find out which solution is the best for me.