views:

76

answers:

0

I have a grid (not data grid) in Silverlight that I build in memory.

I want to be able to pass the grid to a method that will return a parent grid with multiple child grids containing the children in the original grid. The method should split the original grid up into multiple grids whenever the total height of the children in the grid exceeds 1100 pixels.

I have a method that will do this, but I am looking for a more simplified, cleaner approach, and would appreciate any suggestions.

My current method is below. The problem with this method is that it only looks for top-level children. In other words, my grid may contain multiple containers that contain children etc., so I need all elements within the grid to be iterated through.

public static Grid PaginateGrid(this Grid source)
    {
        double totalHeight = 0;

        var parentGrid = new Grid();

        var childGrid = new Grid();

        int parentGridRowCount = 0;

        int childGridRowCount = 0;

        foreach (var element in source.Children)
        {
            if (element is FrameworkElement)
            {
                ((FrameworkElement)element).MeasureAndArrange();

                childGrid.MeasureAndArrange();

                if ((childGrid.DesiredSize.Height + element.DesiredSize.Height)>1100)
                {
                    parentGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                    parentGrid.Children.Add(childGrid);

                    Grid.SetRow(childGrid, parentGridRowCount);

                    parentGridRowCount++;

                    childGridRowCount = 0;

                    childGrid = new Grid();

                    childGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                    childGrid.Children.Add(element);

                    childGrid.MeasureAndArrange();

                    totalHeight = childGrid.DesiredSize.Height;

                    childGridRowCount++;
                }
                else
                {
                    childGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                    childGrid.Children.Add(element);

                    Grid.SetRow((FrameworkElement)element, childGridRowCount);

                    childGridRowCount++;

                    childGrid.MeasureAndArrange();

                    totalHeight = childGrid.DesiredSize.Height;
                }
            }
        }

        return parentGrid;
    }