How do I load user controls dynamically?

Muhammad Adnan picture Muhammad Adnan · Nov 21, 2009 · Viewed 53.2k times · Source

How can I load a user control[s] in a window dynamically (using code at runtime)?

Answer

Richard Szalay picture Richard Szalay · Nov 21, 2009

I'd highly recommend having a look at Prism, since composite user interfaces is what it's for. However, since this would require you refactoring your entire application, I'll also answer your question directly.

If you want a single user control in a container, put a ContentControl in your XAML and then set the Content property. If you are using a view model, you could bind Content to a FrameworkElement property on the view model:

contentControlInstance.Content = new CustomUserControl();

If you want multiple controls in a list, use an ItemsControl and assign an ObservableCollection<> to the ItemsSource property. If you are using a view model, you could bind ItemsSource to an ObservableCollection property on the View Model.

Then you can just add/remove views from that ObservableCollection:

private ObservableCollection<FrameworkElement> views = 
    new ObservableCollection<FrameworkElement>();

private void Initialize()
{
    itemsControl.ItemsSource = views;
}

private void AddView(FrameworkElement frameworkElement)
{
    views.Add(frameworkElement);
}