views:

163

answers:

2

I would like to create simple objects at runtime (textbox, label, etc) and add them to a Grid in my WPF application. My problem is that I need to define these in the app.config file. I am reading in the config data by using the “ConfigurationManager.GetSection” method. Shown below is an example of the XML that defines two textboxes. The Key values are always defined as Labels so the following defines two labels called “ID:” and “Name:” and two associated TextBoxes

<HardwareControls>
    <add key="ID:" value="System.Windows.Controls.TextBox"/>
    <add key="Name:" value="System.Windows.Controls.TextBox"/>
</HardwareControls>

At the moment I use the following code to create a TextBox object but need to modify it so that the control types are defined by the config data and not hardcoded. Can anyone help in how I would go about doing this based on me knowing the control type as defined by a string?

TextBox tb1 = new TextBox();
tb1.Width = 100;
tb1.SetValue(Grid.ColumnProperty, 1);
tb1.SetValue(Grid.RowProperty, i);

I can also see a situation where I may want to define additional values such as the textbox width in the config file. Is there a better solution to store this in the app.config as it looks like the “GetSection” method only supports a key/value pair (I may be rog in that assumption as I haven’t read too much about this yet).

+1  A: 

You can use Activator.CreateInstance

Example:

string typeName = "System.Windows.Controls.TextBox";
Type type = Type.GetType(typeName);
object control = Activator.CreateInstance(type); // control is your TextBox
bniwredyc

related questions