I have some code that dynamically add button to StackPanel. I want to do this action be using the binding to some object that contain list of strings. The number of the button that need to be added to the StackPanel is like the number of the string in the list ==> each button content need to be as string in the list.
How can i do it using binding ? How can i make the connection between the string in the list and the object in the stackpanel 开发者_JAVA百科?
I define the DataContext to be the list - but i don't know how make each item in the stackpanel to be with string from the list.
thanks for any help.
You use an ItemsControl
(which by default uses a Stackpanel
to place its items)
<ItemsControl ItemsSource="{Binding ListOfStringsProperty}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}" />
</DataTemplate>
</ItemsControl>
</ItemsControl>
The real trick though would be making something useful happen when the button is clicked. The most basic approach would be to have a Button_Click
event in the code-behind.
Edit: "How can I change the orientation to Horizontal"
<ItemsControl ItemsSource="{Binding ListOfStringsProperty}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}" />
</DataTemplate>
</ItemsControl>
</ItemsControl>
精彩评论