Loading User Controls Dynamically in Silverlight

When you develop Silverlight web sites you may need to change the content that’s shown in the Silverlight page programmatically, normally changing the layout controls or child controls etc..

In the above image you can see three navigation button’s and when you press each button the content will load dynamically from each separate user control XAML file (shown right side of the image) and render the content inside the canvas.

The below few lines of code which loads the control loading  dynamically and render in to the canvas control

 Type type = this.GetType();
 Assembly assembly = type.Assembly;
 UserControl newPage = (UserControl)assembly.CreateInstance(type.Namespace + "." + "ControlName"); //replace with your user control class name

In the each  button control I am setting the datacontext attribute value as the User Control Class Name ie DataContext=”HomeControl”

XAML Markup

<Canvas Grid.Row="0" Grid.Column="0" Background="Black">
<Button Width="100" DataContext="HomeControl" Canvas.Top="50" Click="Navigation_Click" Canvas.Left="25" Content="Home"/>
<Button Width="100" DataContext="AboutControl" Canvas.Top="50" Click="Navigation_Click" Canvas.Left="140" Content="About"/>
<Button Width="100" DataContext="ContactControl" Canvas.Top="50" Click="Navigation_Click" Canvas.Left="255" Content="Contact"/>

<Canvas Name="canvasBody" Grid.Row="1"  Grid.Column="0" Background="Black" />

Code behind

 public DefaultPage()
 RenderControl("HomeControl"); //load default control for home page.

 private void Navigation_Click(object sender, RoutedEventArgs e)
 Button btn = sender as Button;
 if (btn != null && btn.DataContext != null)

 void RenderControl(string currentControl)
 Type type = this.GetType();
 Assembly assembly = type.Assembly;
 UserControl newPage = (UserControl)assembly.CreateInstance(type.Namespace + "." + currentControl);

Hope this will help and If you have any comments, please feel free to write your feedback.



8 thoughts on “Loading User Controls Dynamically in Silverlight

  1. I have user control that i tried to read. But it is not creating the instance.it returns null value. what else i should do. please let me know..Thank you

  2. Hi,
    Thanks for loading Usercontrol dynamically, but my qustion, If the UserControl is not part of XAP file, Then we need to load XAP on need basis and try instante usercontrol, which make XAP light weight .

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s