wpf 读取xml文件后在WPF xaml文件/xaml.cs文件中动态创建按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16329584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically creating buttons in WPF xaml file/xaml.cs file after reading an xml file?
提问by Coder
I am new to WPF,
我是 WPF 的新手,
Problem Statement: I have a xml file that gives me the number of items that i need to create, for each item, i need a button. If there are 20 items---> on loading the xaml file, the xml will be read, count(of number of items) will be read and created.
问题陈述:我有一个 xml 文件,它给出了我需要创建的项目数,对于每个项目,我需要一个按钮。如果有 20 个项目---> 在加载 xaml 文件时,将读取 xml,将读取和创建 count(of items)。
Is there a way to do this in xaml file?
有没有办法在 xaml 文件中做到这一点?
回答by jacob aloysious
Here is a simple/quick fix:
这是一个简单/快速的修复:
Expose a Panel (say StackPanel) in the Xamland add the new buttons to them as Childrenon run time...
在 中公开一个面板(比如StackPanel),Xaml并Children在运行时向它们添加新按钮......
MainWindow.xaml:
主窗口.xaml:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Loaded="Window_Loaded">
<StackPanel x:Name="mainPanel"/>
</Window>
MainWindow.xaml.cs
主窗口.xaml.cs
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var buttonNames = new List<string>();
// Parse the XML, Fill the list..
// Note: You could do it the way you prefer, it is just a sample
foreach (var buttonName in buttonNames)
{
//Create the button
var newButton = new Button(){Name = buttonName};
//Add it to the xaml/stackPanel
this.mainPanel.Children.Add(newButton);
}
}
Solution using Data Binding
使用数据绑定的解决方案
MainWindow.xaml:
主窗口.xaml:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" >
<ItemsControl ItemsSource="{Binding YourCollection}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Window>
MainWindow.xaml.cs
主窗口.xaml.cs
public MainWindow()
{
InitializeComponent();
YourCollection = new List<Button>();
// You could parse your XML and update the collection
// Also implement INotifyPropertyChanged
//Dummy Data for Demo
YourCollection.Add(new Button() { Height = 25, Width = 25 });
YourCollection.Add(new Button() { Height = 25, Width = 25 });
this.DataContext = this;
}
public List<Button> YourCollection { get; set; }

