Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

c# - How to generate WPF controls automatically based on XML file?

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...