Binding StackPanel Children to an ObservableCollection

Sturm picture Sturm · May 27, 2013 · Viewed 11.2k times · Source

I have an ObservableCollection of buttons:

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);
        }
    }

I want to bind that collection to my StackPanel (in this example it's a constant collection but eventually it would be variable). This is my 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>

I've read that it can be achieved by using ItemsControl, but I don't know how to finish it. (Do I need to set DataContext in code behind?)

Answer

LPL picture LPL · May 27, 2013

I agree with the comment from @inxs. But to make this work move InitializeComponent() after the creation of myBtCollection

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

    InitializeComponent();
}

or implement INotifyPropertyChanged for myBtCollection.