How to generate WPF controls automatically based on XML file?

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

Leave a Comment