views:

17

answers:

1

I'm trying to have a regular grid rows and columns defined dynamically using databinding in XAML only.

I know I can use code behind for this but I'm looking for a way to do it purely in XAML.

Any thoughts?

+2  A: 

Ok, after much reading around the net I coded the following solution:

public class DynamicGrid : Grid
{
    public static readonly DependencyProperty NumColumnsProperty =
        DependencyProperty.Register ("NumColumns", typeof (int), typeof (DynamicGrid), 
        new PropertyMetadata ((o, args) => ((DynamicGrid)o).RecreateGridCells()));

    public int NumColumns
    {
        get { return (int)GetValue(NumColumnsProperty); }
        set { SetValue (NumColumnsProperty, value); }
    }


    public static readonly DependencyProperty NumRowsProperty =
        DependencyProperty.Register("NumRows", typeof(int), typeof(DynamicGrid),
        new PropertyMetadata((o, args) => ((DynamicGrid)o).RecreateGridCells()));

    public int NumRows
    {
        get { return (int)GetValue(NumRowsProperty); }
        set { SetValue (NumRowsProperty, value); }
    }

    private void RecreateGridCells()
    {
        int numRows = NumRows;
        int currentNumRows = RowDefinitions.Count;

        while (numRows > currentNumRows)
        {
            RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
            currentNumRows++;
        }

        while (numRows < currentNumRows)
        {
            currentNumRows--;
            RowDefinitions.RemoveAt(currentNumRows);
        }

        int numCols = NumColumns;
        int currentNumCols = ColumnDefinitions.Count;

        while (numCols > currentNumCols)
        {
            ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            currentNumCols++;
        }

        while (numCols < currentNumCols)
        {
            currentNumCols--;
            ColumnDefinitions.RemoveAt(currentNumCols);
        }

        UpdateLayout();
    }
}

It works but I'm not sure it is the optimal solution. Any comments on this one?

Stecy