Multi-column StackPanel for Windows Phone 7
Join the DZone community and get the full member experience.
Join For FreeFew days ago I have decided to develop multi-column StackPanel control for one of my projects. Basically, I have created many StackPanels in horizontal orientation inside a StackPanel with vertical orientation. It should be a very simple solution and I am going to share it with you in this post. Same solution could be applied to other Silverlight applications.
I have created a new class MultiColumnStackPanel (check code bellow) that inherit from StackPanel. This new class is using NumberOfColumns property to hold the number of columns for StackPanel. Items property is used to hold UIElement collection. LoadItems method is used to create many single horizontal StackPanels from Items collection. You can add additional handlers to PropertyMetadata of dependency property to handle Items property change events.
public class MultiColumnStackPanel : StackPanel { public int NumberOfColumns { get; set; } public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(Collection<UIElement>), typeof(MultiColumnStackPanel), new PropertyMetadata(new Collection<UIElement>())); public Collection<UIElement> Items { get { return (Collection<UIElement>)GetValue(ItemsProperty); } } public MultiColumnStackPanel() { Orientation = Orientation.Vertical; Loaded += (s, e) => { LoadItems(); }; } void LoadItems() { Children.Clear(); if (Items != null) { StackPanel sp = CreateNewStackPanel(); foreach(UIElement item in Items) { sp.Children.Add(item); if (sp.Children.Count == NumberOfColumns) { Children.Add(sp); sp = CreateNewStackPanel(); } } if (sp.Children.Count > 0) Children.Add(sp); } } private StackPanel CreateNewStackPanel() { return new StackPanel() { Orientation = Orientation.Horizontal }; } }To test this control I had to add the code bellow to one of XAML pages. Result can be seen on the image above (in the beginning of this post).
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <local:MultiColumnStackPanel x:Name="customStackPanel" NumberOfColumns="2" Margin="0,8,0,-8"> <local:MultiColumnStackPanel.Items> <Rectangle Height="80" Width="200" Margin="10,0,0,0" Fill="Green" /> <Rectangle Height="80" Width="200" Margin="10,0,0,0" Fill="Green" /> <Rectangle Height="80" Width="200" Margin="10,10,0,0" Fill="Green" /> <Rectangle Height="80" Width="200" Margin="10,10,0,0" Fill="Green" /> <Rectangle Height="80" Width="200" Margin="10,10,0,0" Fill="Green" /> </local:MultiColumnStackPanel.Items> </local:MultiColumnStackPanel> </Grid>
Source: http://www.eugenedotnet.com/2011/01/w14-multi-column-stackpanel-for-windows-phone-7/
Opinions expressed by DZone contributors are their own.
Comments