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
 canvasBody.Children.Clear();
 canvasBody.Children.Add(newPage);

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>

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

Code behind

 public DefaultPage()
 {
 InitializeComponent();
 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)
 {
     RenderControl(btn.DataContext.ToString());
 }
 }

 void RenderControl(string currentControl)
 {
 Type type = this.GetType();
 Assembly assembly = type.Assembly;
 UserControl newPage = (UserControl)assembly.CreateInstance(type.Namespace + "." + currentControl);
 canvasBody.Children.Clear();
 canvasBody.Children.Add(newPage);
 }

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

Thanks
Deepu

Advertisements