如何基于XML文件自动生成WPF控件?

我有一个Xml文件告诉我必须添加到表单的控件,但这个Xml动态更改,我需要更新表单。 目前,我可以阅读XML文件,但我不知道是否可以自动创建基于此的表单?

对的,这是可能的。

WPF提供了几种在Xaml或代码中创建控件的方法。

对于您的情况,如果您需要动态创建控件,则必须在代码中创建它们。 您可以使用其构造函数直接创建控件,如下所示:

// 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解析字符串并创建所需的控件:

  // Create a stringBuilder StringBuilder sb = new StringBuilder(); // use xaml to declare a button as string containing xaml sb.Append(@""); // Create a button using a XamlReader Button myButton = (Button)XamlReader.Parse(sb.ToString()); // Add created button to previously created container. stackPanel.Children.Add(myButton); 

现在,您想要使用的两种方法中的哪一种取决于您。

让 – 路易·

您可以通过wpf中的代码轻松添加控件,您可以按照本文进行操作 。 值得注意的另一件事是XAML是XML的一种forms,因此您可以将XAML保存为XML文件,这样您就不需要在代码中添加控件,但这取决于应用程序的复杂性。

我是Xaml的新手,但如果您不想将命名空间添加到每个元素字符串,那么要添加到Jean-Louis的答案中,那么您可以使用System.Windows.Markup命名空间执行类似的操作:

  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(@"", itemID, listItems[itemID]); UIElement element = (UIElement)XamlReader.Parse(xaml, context); listBoxElement.Items.Add(element); 

通过Children.Add方法添加控件是我发现的最快的方法,例如

  this.Grid.Add(new TextBox() { Text = "Babau" });