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"> <asp:Silverlight ID="MyCommentsControl" runat="server" Source="~/ClientBin/MyCommentsApp.xap" MinimumVersion="2.0.30523" Width="400" Height="100%" /> </div>
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.
<ItemsControl VerticalAlignment="Top" x:Name="Comments" Grid.Row="1" > <ItemsControl.ItemTemplate> <DataTemplate> <my:Comment x:Name="CommentItem"/> </DataTemplate> </ItemsControl.ItemTemplate> </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()
{
InitializeComponent();
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;
this.Comments.UpdateLayout();
}
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!
Posted by Jordan 
.png)



