Introduction:
In real life there are cases where we need to display data like student name as a grid. i.e. student name should be displayed in first horizontally up to say 3 columns and after that names should be displayed in new row and so on. To create this layout Silverlight does not have any in-built control. You can use list-box control to display in names in a column but we cannot display names as a grid. For that we have to make use of ItemsControl and DataTemplate concept of Silverlight.
Using the code:
• Add an “ItemsControl” in XAML file and set “StackPanel” as the panel template for the control
<ItemsControl x:Name="icVertical" Margin="10,10,0,0" HorizontalAlignment="Center">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel></StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
• Define “DataTemplate” to be used to display the data
<DataTemplate x:Key="innerDataTemplate">
<Border BorderBrush="LightBlue" BorderThickness="1" Margin="10,10,10,10" >
<StackPanel >
<TextBlock Text="{Binding}"></TextBlock>
</StackPanel>
</Border>
</DataTemplate>
• Define “DataTemplate” to be used as panel template for the internal items control
<ItemsPanelTemplate x:Key="innerItemsPanelTemplate">
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
• Now in the code, create a new ItemsControl control, set its data template as “innerDataTemplate” and panel template as “innerItemsPanelTemplate”. Set “ItemsSource” property of the newly created ItemsControl and add the control to the ItemsControl defined in the XAML
icVertical.Items.Clear();
int noOfColumns = 4;
List<XElement> listElements = (List<XElement>)result.Elements("FriendId").ToList();
if (listElements.Count > 0)
{
for (int i = 0; i <= listElements.Count / noOfColumns; i++)
{
ItemsControl itemControl = new ItemsControl();
itemControl.ItemTemplate = (DataTemplate)this.Resources["innerDataTemplate"];
itemControl.ItemsPanel = (ItemsPanelTemplate)this.Resources["innerItemsPanelTemplate"];
if (i == listElements.Count / noOfColumns)
{
int remainingElements = listElements.Count - (i * noOfColumns);
itemControl.ItemsSource = listElements.GetRange(i * noOfColumns, remainingElements);
}
else
{
itemControl.ItemsSource = listElements.GetRange(i * noOfColumns, noOfColumns);
}
icVertical.Items.Add(itemControl);
}
}