MAUI中Grid通过RowDefinitions和ColumnDefinitions定义行列尺寸策略:Auto自适应内容、固定值以dp为单位、星号*按比例分配;子控件用Grid.Row/Grid.Column定位,支持跨行跨列;代码中需手动调用Grid.SetRow等方法设置位置;未定义行列则默认1行1列,调试可启用ShowGridLines。

MAUI 中的 Grid 是最常用、最灵活的布局容器之一,设置行(RowDefinitions)和列(ColumnDefinitions)是它的核心用法。关键在于理解“定义”不是直接写宽高,而是用 GridLength 描述每行/列的**尺寸策略**。
在 XAML 中,通过 Grid.RowDefinitions 和 Grid.ColumnDefinitions 集合来声明。每个 RowDefinition 或 ColumnDefinition 指定一行或一列的行为:
100):单位为设备独立像素(dp),固定大小* = 等分,2* = 占两份示例:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="100" />
<RowDefinition Height="2*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
</Grid>使用附加属性 Grid.Row、Grid.Column(从 0 开始计数)定位控件位置:
Grid.Row="1" 表示放在第 2 行(索引为 1)Grid.Column="0" 表示放在第 1 列(索引为 0)Grid.RowSpan="2" 或 Grid.ColumnSpan="3"
例如让一个按钮占满第 0 行全部三列:
<Button Text="全宽按钮" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" />
适合运行时根据数据调整布局:
var grid = new Grid();
grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(2, GridUnitType.Star) });
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(100) });
<p>// 添加子元素并设置位置
var label = new Label { Text = "动态添加" };
Grid.SetRow(label, 1);
Grid.SetColumn(label, 0);
grid.Add(label);注意:Grid.Add(child) 默认加到第 0 行第 0 列;必须手动调用 Grid.SetRow() 等方法才能准确定位。
实际开发中容易忽略的细节:
RowDefinitions 或 ColumnDefinitions?默认只有 1 行 1 列,所有子控件会堆叠在左上角Auto 行/列里放了 VerticalOptions="Fill" 的控件?它不会撑开 Auto 行——Auto 只看内容自身所需尺寸Auto;想“至少 80 宽,有剩余再扩展”?目前 MAUI 不支持 MinWidth,需用 GridLength.Star + 内部嵌套 StackLayout 控制最小尺寸Grid.ShowGridLines="True"(仅 Debug 模式有效,XAML 中加即可)基本上就这些。Grid 看似简单,但行列表达式组合起来能实现绝大多数界面结构,熟练掌握 Auto、*、数字 三种模式,就能稳住大部分布局需求。
以上就是C# MAUI中的Grid布局怎么设置行和列 MAUI Grid教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号