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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With