Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a type of "class" in C#?

Tags:

c#

casting

I am wondering if it is possible to do something. I have a function that reads an xml file and adds controls to a form based on the contents on the file. An xml node like this will create it:

<Button Top="300" Left="100">Automatic</Button>

I have a function that saves the controls back to the xml file if I have added any in an edit mode. It is working, but I am wondering if there is an easier way. Currently, I have code that looks like this to create an instance of each control:

            switch (xmlchild.Name)
            {
                // Create a new control whose type is specified.
                case "Button":
                    c = new Button();
                    break;
                case "Label":
                    c = new Label();
                    break;
                default:
                    c = null;
                    break;
            }

But, when I want to use more types of controls, I will need to keep adding switch cases. Can I do something that will just take the text and add a control of that type? I would appreciate any feedback!

Thanks!

like image 971
TonyShell Avatar asked Jun 29 '10 15:06

TonyShell


2 Answers

If you control the contents of the XML file, then yes. You could use:

string fullNameSpace = "System.Windows.Controls.";
Type controlType = Type.GetType( fullNameSpace + xmlchild.Name );
if( controlType != null )
{
  // get default constructor...
  ConstructorInfo ctor = controlType.GetConstructor(Type.EmptyTypes);
  object control = ctor.Invoke(null);
}

You could also use the Activator class to clean this up a bit:

object control = Activator.CreateInstance( "System.Windows.Presentation", 
                                           xmlchild.Name );

Alternatively, if you can create a valid XAML file, you could use XamlReader to restore the control tree.

like image 183
LBushkin Avatar answered Sep 22 '22 15:09

LBushkin


You can use some convention to save yourself some code. Basically, use reflection to create an instance of whatever control you want, passing in the code from the XML. Something like:

Activator.CreateInstance(xmlchild.Name, ...)

Just fill in the right bits and a lot of that code goes away.

like image 30
CubanX Avatar answered Sep 24 '22 15:09

CubanX