如何基于XML文件自动生成WPF控件? [英] How to generate WPF controls automatically based on XML file?
问题描述
我有一个Xml文件,该文件告诉我必须添加到表单的控件,但是此Xml动态更改,因此我需要更新表单。
当前,我可以读取XML文件,但是我不知道是否可以基于该文件自动创建表单?
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 ?
推荐答案
是的。
WPF提供了几种方法
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);
或者您可以将控件创建为包含xaml的字符串,并使用XamlReader解析该字符串并创建所需的控件:
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.
让·路易
这篇关于如何基于XML文件自动生成WPF控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!