我想要获取一个对象集合,并将其绑定到一个StackPanel,所以基本上如果该集合有4个元素,在堆栈面板中应该会产生4个按钮。
我试过this...But,但我不认为这是正确的方法。在过去,我使用DataTemplated来实现这种想法。如果我错了,请纠正我。
这是我的假模型
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>
它确实绑定了,但我只有一个按钮,而不是4个按钮……
想法?
发布于 2010-07-29 04:02:57
好吧我已经弄明白了..。使用ItemsControl
解决了问题...
<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>
https://stackoverflow.com/questions/3356719
复制相似问题