76

I want to take a collection of objects and bind it to a StackPanel so basically if the collection has 4 elements, inside the stack panel that should produce 4 buttons lets say.

I tried this...But I dont think its the correct approach anyway. I used DataTemplated to do this type of idea in the past.. please correct me if I am wrong.

Here is my fake model

public class MockModel
{
   public ObservableCollection<MockNode> Nodes;

   public MockModel()
   {
      Nodes = new ObservableCollection<MockNode>();
   }
}

public class MockNode
{
   public MockNode()
   {
   }

   private string itemname;
   public string ItemName
   {
      get { return this.itemname; }
      set { this.itemname = value; }
   }
}

In code I set the DataContext like this...

// Init Model
MockModel myModel = new MockModel();

for (int i = 0; i < 4; i++)
{
   MockNode mn = new MockNode();
   mn.ItemName = String.Format("Node {0}", i);
   myModel.Nodes.Add(mn);
}
// Set DataContext for StackPanel
Stack.DataContext = myModel.Nodes;

And the xaml

<StackPanel x:Name="tStack">
   <ItemsControl ItemsSource="{Binding Nodes}">
      <ItemsControl.Template>
         <ControlTemplate>
            <Button Content="{Binding ItemName}"/>
         </ControlTemplate>
      </ItemsControl.Template>
   </ItemsControl>
</StackPanel>

IT does bind but instead of 4 buttons I only get one button....

Ideas?

Gabe
  • 49,577
  • 28
  • 142
  • 181

1 Answers1

168

Alright I have figured it out... Using an ItemsControl solved the problem...

<ItemsControl x:Name="tStack" ItemsSource="{Binding Items}">
   <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
         <StackPanel Orientation="Horizontal"/>
      </ItemsPanelTemplate>
   </ItemsControl.ItemsPanel>
   <ItemsControl.ItemTemplate>
      <DataTemplate>
         <Button Content="{Binding ItemName}"/>
      </DataTemplate>
   </ItemsControl.ItemTemplate>
</ItemsControl>
sarh
  • 6,371
  • 4
  • 25
  • 29
Gabe
  • 49,577
  • 28
  • 142
  • 181
  • It's not always necessary, but for some further customizations you'll need to set the "IsItemsHost" property on StackPanel. – MatrixManAtYrService Apr 11 '14 at 12:01
  • 10
    Where are you setting `ItemsSource`? Is this XAML wrapped in a ``? – IAbstract Nov 30 '14 at 04:43
  • 4
    @IAbstract ItemsSource is set in the `ItemsControl`. – Lynn Crumbling Apr 16 '15 at 19:31
  • 2
    In Your example, there are only 4 buttons, but if You have many items in the collection to be bound, You may want to use `VirtualizingStackPanel` in the `ItemsPanelTemplate` as mentioned here: http://stackoverflow.com/a/1525874/232530 – Lukasz M May 12 '17 at 16:24