Expand a Silverlight control

To re-size the container DIV of a Silverlight control so that it stretches depending on how much content is in the Silverlight application is quite easy.

In this example we will use an ItemsControl which loads comments from a WCF service. As more comments are added we want my Silverlight control to continually expand.

Silverlight control in the ASPX page

<div id="commentsSection">

Note the DIV with an ID around the Silverlight control. Also the Silverlight control height property is set to 100%.

ItemsControl Example

Inside the Page.xaml file create the ItemsControl.


The my:Comment user control simply shows a few TextBlocks in a StackPanel.

Wire up resize events and logic

When the ItemsSource is set on the ItemsControl we want the Silverlight control itself to expand and push down the HTML page. To do this we need to hook up an event handler to the ItemsControl SizeChanged event.

public Page()
	this.Comments.SizeChanged += new SizeChangedEventHandler(Comments_SizeChanged);

void Comments_SizeChanged(object sender, SizeChangedEventArgs e)
	double acutalHeight = this.Comments.ActualHeight;
	HtmlPage.Document.GetElementById("commentsSection").SetStyleAttribute("height", string.Format("{0}px", acutalHeight));

Add the SizeChanged under the call to InitializeComponent(). Within the SizeChanged event handler you can see the code to get the ActualHeight of the comments. Next the element we created in the ASPX page is updated using the JavaScript bridge.

Bind data and call UpdateLayout()

Finally we need to bind some data to the ItemsControl.

void cClient_GetCommentsCompleted(object sender, SLComments.CommentsService.GetCommentsCompletedEventArgs e)
	Comments.ItemsSource = e.Result;

Take special note here of the call to this.Comments.UpdateLayout();. This must be called after the ItemsSource is set to ensure the SizeChanged event is fired.

Every time you bind the ItemsSource the parent DIV will re-size and because the Silverlight control height property is set to 100% in the ASPX page it will re-size with it!

19 thoughts on “Expand a Silverlight control

  1. This does not …fly well for me.

    When the control ItemControl is created, One has no idea what will be the name of the tab. Does this mean that the ItemControl user control has the requirement that “if you want to use me, you have to put me inside a div with a name of CommentsSection?”

    1. Hey,

      No, it doesn’t mean that it must be in this DIV – the DIV id is just a way to get a reference to the parent container in the HTML so the entire Silverlight control can be dynamically resized as the content within it grows. There may be other ways you can achieve the same result without naming the DIV…

  2. Hi, i believe that i noticed you visited my blog thus i came to go back the favor?.I’m trying to find things to improve my web site!I suppose its ok to use a few of your ideas!!

Comments are closed.