When to use Canvas

Wednesday, May 21, 2008

On a Microsoft internal discussion list Dave Relyea gave a very well described reasoning of when to use a Canvas:

The usage of Canvas elements in controls and layout containers is an anti-pattern and should be avoided. Unless you have some sort of user drawing/design/charting surface or something where thinking in any terms other than X and Y is unnatural, you should not be using a Canvas anywhere.

Canvas always returns 0,0 for its desired size in MeasureOverride.

For layout purposes, no space will ever be allocated for a Canvas, even if the Canvas has a Width and Height set.

Canvas returns exactly what it was given in ArrangeOverride.

This means that layout will never impose a clip on the Canvas, even if the Canvas has a Width and Height set and those exceed the space that layout is giving it.

Canvas measures its children at infinity,infinity.

Children can be as big as they want to be. This may not be bad in and of itself, but if you want the children to fit into a container, you can just let layout do it for you.

Canvas arranges its children at their desired size, and places them at their Canvas.Top/Left.

The Children of a Canvas can effectively be anywhere on the screen, and will not cause clipping (although they will be clipped by other explicit or layout clips in the ancestor chain). If this is a behavior that you need, you can use a TranslateTransform instead.

Clips may be explicitly applied to the Canvas, of course, but that is not the solution, and clipping is expensive.

EDIT: Dave just dusted off his blog and posted what is quoted above. Here’s is Why [Dave] Doesn’t Like Canvas .

HTMLhtml

This work is licensed under CC BY-NC-SA 4.0

Silverspine Technology

Sometimes Analytics Suck