【问题标题】:Using XAML and Silverlight 4, is there a way to build up a dynamic GRID rows and columns from databinding?使用 XAML 和 Silverlight 4,有没有办法从数据绑定构建动态 GRID 行和列?
【发布时间】:2011-10-03 20:11:12
【问题描述】:

我正在尝试仅使用 XAML 中的数据绑定动态定义常规网格行和列。

我知道我可以为此使用代码,但我正在寻找一种纯粹在 XAML 中执行此操作的方法。

有什么想法吗?

【问题讨论】:

  • 也许可以在后面的代码中发布您的操作方式。我的问题是数据源是什么样的。它会有列名的数据注释吗?自动生成列在哪里失败?

标签: silverlight xaml dynamic silverlight-4.0


【解决方案1】:

好的,在网上大量阅读后,我编写了以下解决方案:

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();
    }
}

它有效,但我不确定它是否是最佳解决方案。这个有cmet吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多