0

I have some UserControls named a1, a2, b1, b2... and I want to load one of them depending of the value of two variables. For example, if var1 = a, var2 = 1, the UserControl named a1 will be loaded.

Is there a way of doing this? Perhaps some other alternate approach?

A switch statement is not a viable option here, because there will be like 200 different UserControls.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
DonPituti
  • 1
  • 1
  • 1

3 Answers3

3

You can use .NET Reflection to load a control by its String value.

you can use some code like this to create the object on the fly.

using System.Reflection;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            //this is the full namespace name of UserControl.
            // you could use something like String.Format("WpfApplication1.{0}", "uc1") to put in a function and pass through.
            string ucName = "WpfApplication1.uc1";

            Type newType = Type.GetType("WpfApplication1.uc1", true, true);

            object o = Activator.CreateInstance(newType);

            //Use the object to how ever you like from here on wards.


        }
    }
}
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Robbie Tapping
  • 2,516
  • 1
  • 17
  • 18
  • This worked for me I just needed to add something like `stkPanel.Children.Add(UIElment o);` to dynamically load up my user control when I clicked the button that had the name of my user control in it – KyleMassacre Jun 28 '14 at 20:05
2

You can use Activator.CreateInstance to create the UserControl instance from string name of the type.

But you would better solve this with styling or control templates - these are both great tools to reduce amount of code and its complexity in WPF.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Matěj Zábský
  • 16,909
  • 15
  • 69
  • 114
0

A powerful possibility is to use XamlReader to create your controls.

In your example this is not a desired, but a big advantage of using the xaml-reader is that you can also initialize properties of your control during initialization through the xamlReader.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
HCL
  • 36,053
  • 27
  • 163
  • 213