我有一个 ObservableCollection 按钮:
public partial class MainWindow : Window
{
public ObservableCollection<Button> myBtCollection { get; set; }
public MainWindow()
{
InitializeComponent();
myBtCollection = new ObservableCollection<Button>();
Button bot1 = new Button { Width = 200, Height = 25, Content = "Boton 1" };
Button bot2 = new Button { Width = 150, Height = 50, Content = "Boton 2" };
Button bot3 = new Button { Width = 100, Height = 100, Content = "Boton 3" };
myBtCollection.Add(bot1);
myBtCollection.Add(bot2);
myBtCollection.Add(bot3);
myBtCollection.Add(bot1);
myBtCollection.Add(bot3);
myBtCollection.Add(bot2);
myBtCollection.Add(bot1);
}
}
我想将该集合绑定到我的 StackPanel(在此示例中,它是一个常量集合,但最终它将是可变的)。这是我的 XAML:
<Window x:Name="mainWindow" x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel x:Name="stack">
</StackPanel>
<ItemsControl Width="Auto"
Height="Auto"
ItemsSource="{Binding ElementName=mainWindow, Path=myBtCollection}">
</ItemsControl>
</Grid>
</Window>
我读过它可以通过使用 ItemsControl 来实现,但我不知道如何完成它。(我需要在后面的代码中设置 DataContext 吗?)