2011-09-21 161 views
1

我有一些动态添加按钮到StackPanel的代码。 我想做这个动作是使用绑定到一些包含字符串列表的对象。 需要添加到StackPanel的按钮的数量就像列表中的字符串的数量==>每个按钮的内容都需要作为列表中的字符串。如何动态添加按钮到StackPanel

我怎样才能使用绑定? 如何使列表中的字符串与堆栈面板中的对象之间建立连接?

我将DataContext定义为列表 - 但我不知道如何使堆栈面板中的每个项目都与列表中的字符串一致。

感谢您的任何帮助。

回答

2

您使用ItemsControl(默认情况下使用Stackpanel把其项目)

<ItemsControl ItemsSource="{Binding ListOfStringsProperty}"> 
    <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <Button Content="{Binding}" /> 
      </DataTemplate> 
    </ItemsControl> 
</ItemsControl> 

真正的技巧,虽然将作出单击该按钮时,有用的事情发生。最基本的方法是在代码隐藏中有一个Button_Click事件。

编辑: “我怎样才能改变方向,以横”

<ItemsControl ItemsSource="{Binding ListOfStringsProperty}"> 
    <ItemsControl.ItemsPanel> 
      <ItemsPanelTemplate> 
       <StackPanel Orientation="Horizontal" /> 
      </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <Button Content="{Binding}" /> 
      </DataTemplate> 
    </ItemsControl> 
</ItemsControl> 
+1

@Yanshof:见我的编辑。 – AnthonyWJones