I’m wondering how one could use template databinding to accomplish what the following code produces (a grid of checkboxes with some associated text):
int tbIndex = 0; for (int i = 1; i < 5; i++) { StackPanel pan = new StackPanel(); pan.Orientation = Orientation.Horizontal; pan.Margin = new Thickness(3); pan.Name = 'RowPanel' + i; for (int j = 0; j < 3; j++) { CheckBox cb = new CheckBox(); TextBlock block = new TextBlock(); block.Width = 75; block.Text = 'Item ' + (++tbIndex).ToString(); pan.Children.Add( cb ); pan.Children.Add( block ); } ContentPanel.Children.Add( pan ); }
In ASP.NET, for example, one could use a DataList and set the repeat direction to horizontal and bind. Is there an equivalent way that is less imperative and more declarative (ie. done up front with a template and using generic ‘databinding’ facilities)?
AnthonyWJones has it right that the Wrap Panel is a good approach but Kent went through the trouble of demonstrating how once could use the ItemSource (albeit with the StackPanel which doesn’t achieve the goal). As such I’ll post the code which demonstrates the declarative equivalent:
A small gotcha is that the DataTemplate expects a single child so using a StackPanel with horizontal orientation keeps things flowing.