我是WPF的新手,
问题陈述:我有一个xml文件,它给了我需要创建的项目的数量,对于每个项目,我需要一个按钮。如果在加载xaml文件时有20个项目->,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);
}
}
使用数据绑定的解决方案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; }