Archive for November, 2010

OMG, Custom Silverlight Panels

Ok so the following doesn’t extend WrapPanel except to add the correct template for the ‘column’. Examples of completely custom panels can be found here and here.

public class WrapInColumnsPanel : WrapPanel
    {

        public readonly DependencyProperty NumberOfColumnsProperty =
            DependencyProperty.Register(
            "NumberOfColumns", typeof(Double),
            typeof(WrapInColumnsPanel), null);

        public double NumberOfColumns
        {
            get { return (double)GetValue(NumberOfColumnsProperty); }
            set { SetValue(NumberOfColumnsProperty, value); }
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            for (int i = 0; i < Children.Count; i++)
            {
                Double DbCurrentChildPosition = (double)i + 1;
                if (DbCurrentChildPosition % NumberOfColumns == 0.0)
                {
                    //Child is in the last column
                    ContentPresenter cp = Children[i] as ContentPresenter;
                    cp.HorizontalAlignment = HorizontalAlignment.Right;
                    cp.ContentTemplate = App.Current.Resources["ContentGridDataTemplateRight"] as DataTemplate;
                    cp.Arrange(new Rect(new Point(0, 0), cp.DesiredSize));
                }
                else if (DbCurrentChildPosition == 1 || (DbCurrentChildPosition - 1) % NumberOfColumns == 0.0)
                {
                    //Child is in the first column
                    ContentPresenter cp = Children[i] as ContentPresenter;
                    cp.HorizontalAlignment = HorizontalAlignment.Right;
                    cp.ContentTemplate = App.Current.Resources["ContentGridDataTemplateLeft"] as DataTemplate;
                    cp.Arrange(new Rect(new Point(0, 0), cp.DesiredSize));
                }
                else
                {
                    //Child is in the centre
                    ContentPresenter cp = Children[i] as ContentPresenter;
                    cp.HorizontalAlignment = HorizontalAlignment.Right;
                    cp.ContentTemplate = App.Current.Resources["ContentGridDataTemplateCenter"] as DataTemplate;
                    cp.Arrange(new Rect(new Point(0, 0), cp.DesiredSize));
                }
            }
            return base.ArrangeOverride(finalSize);
        }
    }