You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Prism与Xamarin:如何在运行时访问Grid并添加行

动态为Xamarin Grid添加行及内容的解决方案

嗨,我来帮你搞定这个问题!既然你已经在XAML里定义好基础Grid结构了,要在运行时动态添加行其实很简单,分两步走就行:先添加行定义,再为每一列填充控件。下面给你具体的实现方法:

步骤1:编写添加行的方法

在对应的代码后台文件(比如你的Page的.xaml.cs)里,创建一个用来添加新行的方法。这个方法会先给Grid添加新的RowDefinition,然后为新行的每一列创建并添加控件(这里用Label举例,你可以根据需求换成Entry、Button等)。

private void AddNewRow(string col1Content, string col2Content, string col3Content, string col4Content)
{
    // 1. 添加新的行定义,默认高度是Auto,也可以手动设置
    var newRowDef = new RowDefinition { Height = GridLength.Auto };
    SourceGrid.RowDefinitions.Add(newRowDef);
    
    // 获取新行的索引(因为RowDefinitions是集合,最后一个就是刚加的)
    int newRowIndex = SourceGrid.RowDefinitions.Count - 1;

    // 2. 为每一列创建控件并添加到Grid中
    // 第一列
    var col1Label = new Label 
    { 
        Text = col1Content, 
        Margin = new Thickness(8),
        VerticalOptions = LayoutOptions.Center
    };
    Grid.SetRow(col1Label, newRowIndex);
    Grid.SetColumn(col1Label, 0);
    SourceGrid.Children.Add(col1Label);

    // 第二列
    var col2Label = new Label 
    { 
        Text = col2Content, 
        Margin = new Thickness(8),
        VerticalOptions = LayoutOptions.Center
    };
    Grid.SetRow(col2Label, newRowIndex);
    Grid.SetColumn(col2Label, 1);
    SourceGrid.Children.Add(col2Label);

    // 第三列
    var col3Label = new Label 
    { 
        Text = col3Content, 
        Margin = new Thickness(8),
        VerticalOptions = LayoutOptions.Center
    };
    Grid.SetRow(col3Label, newRowIndex);
    Grid.SetColumn(col3Label, 2);
    SourceGrid.Children.Add(col3Label);

    // 第四列
    var col4Label = new Label 
    { 
        Text = col4Content, 
        Margin = new Thickness(8),
        VerticalOptions = LayoutOptions.Center
    };
    Grid.SetRow(col4Label, newRowIndex);
    Grid.SetColumn(col4Label, 3);
    SourceGrid.Children.Add(col4Label);
}

步骤2:触发添加行的操作

你可以在页面加载时自动添加行,也可以通过按钮点击等事件触发。比如在页面的OnAppearing方法里初始化添加几行测试数据:

protected override void OnAppearing()
{
    base.OnAppearing();
    
    // 页面加载时添加两行示例数据
    AddNewRow("产品ID", "产品名称", "单价", "库存");
    AddNewRow("P001", "无线耳机", "299", "120");
}

如果是按钮点击触发,只需要给按钮绑定点击事件,在事件方法里调用AddNewRow即可:

private void AddRowButton_Clicked(object sender, EventArgs e)
{
    // 这里可以根据输入框等获取内容,或者生成默认数据
    AddNewRow($"P{new Random().Next(100,999)}", "新品", "199", "50");
}

额外注意点

  • 如果你的数据是动态变化的(比如从接口获取),建议配合MVVM模式,用ObservableCollection存储数据,再通过数据绑定来生成Grid的行,这样更符合Xamarin的最佳实践。
  • 如果需要删除行,记得同时移除对应的RowDefinition和Grid.Children里的控件,避免内存泄漏。
  • 可以给RowDefinition设置不同的高度模式:GridLength.Auto(自适应内容)、GridLength.Star(占剩余空间)或者固定数值。

内容的提问来源于stack exchange,提问作者Edward

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 11:12:51