Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

c# - Bind Collection to StackPanel

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

<ItemsControl x:Name="tStack" Grid.Column="0">
   <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
         <StackPanel Orientation="Horizontal"/>
      </ItemsPanelTemplate>
   </ItemsControl.ItemsPanel>
   <ItemsControl.ItemTemplate>
      <DataTemplate>
         <Button Content="{Binding ItemName}"/>
      </DataTemplate>
   </ItemsControl.ItemTemplate>
</ItemsControl>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...