Silverlight Tip: Stretch Canvas to Fill the Screen

I am not sure if this is a bug or by-design but Canvases don’t stretch the way I expect them to – the Grid control seems to resize better.

If you want your Canvas to stretch and Fill its parent, there is an easy way to do this.

1. On initialization, set the Canvas width and height to the Actual width and height of its parent.

myCanvas.Width = ActualWidth ;
myCanvas.Height = ActualWidth ;

2. Wire the SizeChanged event of the parent control

ParentSizeChanged += 
            new SizeChangedEventHandler(Parent_SizeChanged);

3. In the SizeChanged event handler, set the width and height of the canvas again just like you did during initialization

void ParentManager_SizeChanged(object sender, SizeChangedEventArgs e)
{
   myCanvas.Width = ActualWidth;
   myCanvas.Height = ActualHeight;
}

This tip is related to Silverlight 2 Beta 1.

Advertisements

0 thoughts on “Silverlight Tip: Stretch Canvas to Fill the Screen

  1. Warning : In Initialization code, i think there is a mistakemyCanvas.Width = ActualWidth ;myCanvas.Height = ActualWidth ; –> ActualHeightThanks for your tip, it is useful for me

    Like

  2. Warning : In Initialization code, i think there is a mistakemyCanvas.Width = ActualWidth ;myCanvas.Height = ActualWidth ; –> ActualHeightThanks for your tip, it is useful for me

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s