Brian Montfort
Brian Montfort

Reputation: 73

How do I add a UserControl dynamically when all I have is the name of the control in a string format? Silverlight, C#

I'm working on calling different user controls, and the only data that I've been given is a string in which to call the user control that I have created. When I know the name, I can hard code and add that control in the code behind and add it dynamically that way, but when the name of the control is being passed to me via a string, I'm having trouble passing that to my usercontrol object and having it not be null...

Here is my code:

string userControlName = "ReportFilterOptions";                
Type type = this.GetType();
Assembly assembly = type.Assembly;
UserControl c = (UserControl)assembly.CreateInstance(type.FullName + "." + userControlName);
gridReport.Children.Clear();
gridReport.Children.Add(c);

Upvotes: 2

Views: 2053

Answers (1)

Tedd Hansen
Tedd Hansen

Reputation: 12314

Use System.Activator.CreateInstance.

See this example. The important parts are:

// get type of class Calculator from just loaded assembly
Type calcType = testAssembly.GetType("Test.Calculator");

// create instance of class Calculator
object calcInstance = Activator.CreateInstance(calcType);

You could make this more "user friendly" by iterating all the types to match string.

See around line 54 of this file in method UpdateClassList.

Upvotes: 2

Related Questions