How to switch Silverlight UserControls

One of the guys on the official Silverlight community forums posted an interesting question, namely how does one change the currently visible UserControl in a Silverlight 2.0 application. To put things in context the new Silverlight 2.0 project template creates two classes for you: a System.Windows.Application derived class named App with the associated App.xaml and App.xaml.cs files; as well as a System.Windows.Controls.UserControl derived class called Page with the associated Page.xaml and Page.xaml.cs files.

The App class takes care of the initialization and basically you assign a new instance of your Page class to the App.RootVisual property and through the power of Silverlight it appears on your screen. 🙂

So if you wanted to change the currently displayed UserControl for another instance naturally you’d try and set the App.RootVisual property to another instance of a UserControl. This sounds great in theory but it seems that its a single assignment property. Pete Brown’s blog post happens to make mention of this.

So in a quest to solve the problem I’ve implemented a very simple UserControlContainer class that allows the developer to switch controls at runtime without having to deal with the set once RootVisual property.

Simply create a new UserControl called UserControlContainer and copy the following into the UserControlContainer.xaml.cs file:

    public void SwitchControl(UserControl newControl)
        if (newControl != null)
            Height = newControl.Height;
            Width = newControl.Width;

Next set your Application instance RootVisual to an instance of the new UserControlContainer in the Application_Startup method.

    private void Application_Startup(object sender, StartupEventArgs e)
        // Load the main control
        this.RootVisual = new UserControlContainer();
        Page page = new Page();

Then wherever you need to switch out the active control, simply call the following if you are inside App.xaml.cs:

    TestControl1 testControl = new TestControl1();

Or the following if you need to switch controls from elsewhere:

    TestControl1 testControl = new TestControl1();

If you find this useful or find any issues with this method, let me know so I can improve it for all.


Updated 2008-03-13: Added Application_Startup example. Thanks to Maurice for pointing this omission out.

[tags]Silverlight 2.0,code,example[/tags]

Be Sociable, Share!