我是 WPF 新手,
问题陈述:我有一个 xml 文件,它提供了我需要创建的项目数, 对于每个项目,我都需要一个按钮。 如果有20个项目--->加载xaml文件时, 将读取 xml, 将读取并创建 count(项目数)。
有没有办法在 xaml 文件中执行此操作?
最佳答案
这是一个简单/快速的修复:
在Xaml
中公开一个面板(例如StackPanel
),并在运行时将新按钮作为Children
添加到其中...
MainWindow.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
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);
}
}
使用数据绑定(bind)的解决方案
MainWindow.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
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; }
关于wpf - 读取 xml 文件后在 WPF xaml 文件/xaml.cs 文件中动态创建按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16329584/