这是一个示例,用于在运行时(代码隐藏)中databinding
添加多个控件(button
此处)。应该是一个很好的起点。
而且,如果加载表单后数据会发生变化,您可以实现INotifyPropertyChange并相应地更新
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>
主窗口.xaml.cs
public MainWindow()
{
InitializeComponent();
YourCollection = new List<Button>();
//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; }