将集合绑定到 StackPanel [英] Bind Collection to StackPanel
问题描述
我想获取一个对象集合并将其绑定到 StackPanel,所以基本上如果集合有 4 个元素,那么在堆栈面板内应该生成 4 个按钮.
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.
我试过这个...但我不认为它是正确的方法.过去我用DataTemplated做这种类型的想法..如果我错了,请纠正我.
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.
这是我的假模型
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; }
}
}
在代码中,我像这样设置了 DataContext...
// 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;
还有 xaml
<StackPanel x:Name="tStack">
<ItemsControl ItemsSource="{Binding Nodes}">
<ItemsControl.Template>
<ControlTemplate>
<Button Content="{Binding ItemName}"/>
</ControlTemplate>
</ItemsControl.Template>
</ItemsControl>
</StackPanel>
IT 确实绑定,但我只有一个按钮而不是 4 个按钮....
IT does bind but instead of 4 buttons I only get one button....
想法?
推荐答案
好吧,我想通了...使用 ItemsControl
解决了这个问题...
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>
这篇关于将集合绑定到 StackPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!