Question

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?)

Was it helpful?

Solution

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.

OTHER TIPS

  1. The ItemsControl uses a Vertical StackPanel already.
  2. You can't bind data to a StackPanel, which is used for the visual layout.

If you wish to use a different Panel or change the StackPanels orientation you could use the Property "ItemsPanel" on the ItemsControl and set it like this:

<ItemsControl.Style>
            <Style TargetType="{x:Type ItemsControl}">
                <Setter Property="ItemsPanel">
                    <Setter.Value>
                        <ItemsPanelTemplate>
                            <StackPanel Orientation="Horizontal"/>
                        </ItemsPanelTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
 </ItemsControl.Style>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top