开发者

Using XAML and Silverlight 4, is there a way to build up a dynamic GRID rows and columns from databinding?

I'm trying to have a regular grid rows and 开发者_StackOverflow社区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?


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜