将StackPanel子项绑定到ObservableCollection

Stu*_*urm 4 c# wpf xaml binding stackpanel

我有一个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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我想将该集合绑定到我的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>
Run Code Online (Sandbox Code Playgroud)

我已经读过它可以通过使用ItemsControl实现,但我不知道如何完成它.(我需要在代码后面设置DataContext吗?)

LPL*_*LPL 5

我同意@inxs的评论.但是为了使这项工作InitializeComponent()在创建myBtCollection之后移动

public MainWindow()
{
    myBtCollection = new ObservableCollection<Button>();
    ...

    InitializeComponent();
}
Run Code Online (Sandbox Code Playgroud)

或者实现INotifyPropertyChanged接口myBtCollection.