我是WPF新手,
问题陈述:我有一个xml文件,它提供了我需要创建的项目数, 对于每个项目,我需要一个按钮。 如果有20个项目--->在加载xaml文件时, 将读取xml, 将读取并创建计数(项目数)。
有没有办法在xaml文件中执行此操作?
答案 0 :(得分:3)
在StackPanel
中公开一个面板(比如Xaml
),并在运行时将新按钮添加为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; }