Jesse Liberty - Silverlight Geek

By, For and About Silverlight Developers

Did You Know... That Canvas has a default width and height of 0?

If you don't specify otherwise, the Canvas object has a height of 0, a width of 0 and a background of null.

It turns out that this has some very profound effects that I will explore in this and the next couple Tips of the Day. A canvas with a height of 0 and a width of 0:

  • isn't very good at displaying its background color
  • isn't very good at responding to mouse clicks
  • yet, is able to have children outside its bounds!

Each of these three facts can lead to surprises for the unwary programmer.  Let's start, today with the first.  Examine this code,

<Canvas xmlns="http://schemas.microsoft.com/client/2007"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
   <Canvas Name="InnerCanvas"
           Background="LightBlue">
      <Rectangle x:Name="myRect0"
                 Width="100"
                 Height="44"
                 Canvas.Left="0"
                 Canvas.Top="10"
                 StrokeThickness="2"
                 Stroke="Black"
                 Fill="Red" />
   </Canvas>
</Canvas>

On examination it would be reasonable to expect to see a red rectangle with a black border on a light blue background, but what is rendered appears to have no background,

CanvasNoWidth

While the canvas does have a light blue background, it is invisible because the width and height are zero. Thus, the rectangle is actually rendered outside the borders of our 0 x 0 canvas.  To fix this, add an explicit width and height to the canvas,

<Canvas xmlns="http://schemas.microsoft.com/client/2007"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
   <Canvas Name="InnerCanvas"
           Background="LightBlue"
           Width="200"
           Height="200">
      <Rectangle x:Name="myRect0"
                 Width="100"
                 Height="44"
                 Canvas.Left="0"
                 Canvas.Top="10"
                 StrokeThickness="2"
                 Stroke="Black"
                 Fill="Red" />
   </Canvas>
</Canvas>

Hey! Presto! the canvas now encompasses the rectangle and the background color is visible:

CanvasWithWidth

kick it on DotNetKicks.com

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# January 12, 2008 10:13 AM

Jesse Liberty - Silverlight Geek said:

In today&#39;s Tip of the Day I wrote that Canvas&#39;s Height and Width properties default to zero.

# January 12, 2008 2:05 PM

Blogs said:

In today&#39;s Tip of the Day I wrote that Canvas&#39;s Height and Width properties default to zero.

# January 12, 2008 2:57 PM