如何将网格分配给网格

How to assign the grid to a grid

我在 xaml 文件中新建了一个没有任何设置的网格对象。 通过'OnAppearing()'中的'Build_Grid()'导入数据后,我想将'gridview'分配给'Grid_Info'显示在屏幕上,代码'Grid_Info = gridview'不起作用. 我想知道如何实现我的需求?

<ContentPage.Content>
<StackLayout>
<Label Text="AAA" />
<Grid x:Name="Grid_Info">
</Grid>
</StackLayout>
</ContentPage.Content>


    void Build_Grid(Data data)
        {
        Grid gridview = new Grid();
        gridview.RowDefinitions.Add(new RowDefinition() { Height = 40 });
        gridview.Children.Add(data[0],0,0);
        ...
Grid_Info = gridview; //it does not work...
        }

protected override void OnAppearing()
{
Data data = new Data();
...
Build_Grid(data);
}

如果您已经在 XAML 中定义了网格,则无需执行此操作

Grid gridview = new Grid();

而是直接引用 Grid_Info

Grid_Info.RowDefinitions.Add(new RowDefinition() { Height = 40 });
Grid_Info.Children.Add(data[0],0,0);

您可以试试下面的代码。我制作了一个数据 class 以进行测试。它对我有用。

public partial class Page3 : ContentPage
{
    Data[] data;
    public Page3()
    {
        InitializeComponent();
        data = new Data[2];
        data[0] = new Data { view = new Button() { BackgroundColor = Color.Red } }; //data[0]
        data[1] = new Data { view = new Label() { BackgroundColor = Color.Green, Text = "Label" } };//data[1]

    }
    void Build_Grid(Data[] data)
    {
        Grid gridview = new Grid();
        Grid_Info.RowDefinitions.Add(new RowDefinition() { Height = 40 });
        Grid_Info.Children.Add(data[0].view, 0, 0);//show the red button
        Grid_Info = gridview; //it does not work...
    }
    protected override void OnAppearing()
    {
        base.OnAppearing();
        Build_Grid(data);
    }
}
public class Data
{
    public View view { get; set; }
}