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

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in z Silverlight Archives. Bookmark the permalink.