I have an Xml file which tells me the controls that I have to add to a form but this Xml changes dynamically and I need to update the form. Currently, I can read the XML file, but I dont know if it is possible to automatically create forms based on that or not ?
4 Answers
Yes It is possible.
WPF offers several ways of creating controls either in Xaml or in code.
For your case if you need to dynamically create your controls, you'll have to create them in code. You can either create your control directly using their constructors as in:
// Create a button.
Button myButton= new Button();
// Set properties.
myButton.Content = "Click Me!";
// Add created button to a previously created container.
myStackPanel.Children.Add(myButton);
Or you could create your controls as a string containing xaml and use a XamlReader to parse the string and create the desired control:
// Create a stringBuilder
StringBuilder sb = new StringBuilder();
// use xaml to declare a button as string containing xaml
sb.Append(@"<Button xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");
sb.Append(@"Content='Click Me!' />");
// Create a button using a XamlReader
Button myButton = (Button)XamlReader.Parse(sb.ToString());
// Add created button to previously created container.
stackPanel.Children.Add(myButton);
Now for which one of the two methods you want to use really depends on you.
Jean-Louis

- 1,604
- 11
- 16
You can easily add controls via code in wpf, you can follow this article. Another thing worth noting is that XAML is a form of XML so you can you save your XAML to an XML file, that way you wouldn't need to add controls in code, however it depends on the complexity of your application.

- 3,077
- 2
- 25
- 39
I am pretty new to XAML but to add to Jean-Louis's answer if you do not want to add the namespaces to every element string then you can do something like this using the System.Windows.Markup
namespace:
ParserContext context = new ParserContext();
context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
string xaml = String.Format(@"<ListBoxItem Name='Item{0}' Content='{1}' />", itemID, listItems[itemID]);
UIElement element = (UIElement)XamlReader.Parse(xaml, context);
listBoxElement.Items.Add(element);

- 1,893
- 1
- 14
- 16

- 31
- 1
- 3
Adding controls through the Children.Add method is the quickest way i've found, such as for example
this.Grid.Add(new TextBox() { Text = "Babau" });

- 31
- 2