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

Entry控件无法填充父级HorizontalStackLayout的技术问询

问题

我正在构建一个包含标题列和值列的输入表单,标题列包含Label,值列包含HorizontalStackLayout,该布局内可能同时存在Entry和搜索按钮。已将HorizontalStackLayout的HorizontalOptions设为LayoutOptions.Fill且生效,但将Entry的HorizontalOptions设为LayoutOptions.Fill后,Entry并未填充父级布局。

相关代码如下:

//IF THIS IS  A TEXT FIELD
if (cv.GetType() == typeof(Entry)) { ((Entry) cv).HorizontalOptions = LayoutOptions.Fill;
}

//SET CONTROL'S DYNAMIC VIS SETTING
cv.IsVisible = visible;

//IF THIS FIELD IS READONLY
if (trx.is_field_readonly(c)) {
  cv.IsEnabled = false;
}

//ADD CAPTION TO GRID
grid.Add(caption, 0, c);

//USING STACK LAYOUT IN CASE WE NEED TO ADD A SEARCH BUTTON
HorizontalStackLayout hz = new HorizontalStackLayout();
hz.BackgroundColor = Colors.LightGoldenrodYellow;
hz.HorizontalOptions = LayoutOptions.Fill;
hz.Add(cv);

//ADD CONTROL TO GRID
if (trx.is_field_lookup_field(trx.data_field_list[c])) {
  ImageButton search_button = new ImageButton();
  search_button.WidthRequest = 32;
  search_button.HeightRequest = 32;
  search_button.HorizontalOptions = LayoutOptions.Start;
  search_button.Source = "Resources/Images/search.png";
  search_button.BackgroundColor = Colors.LightGray;
  search_button.Padding = 5;
  hz.Add(search_button);
}

//ADD STACKLAYOUT FOR CONTROL(S)
grid.Add(hz, 1, c);

当前界面效果:
界面效果截图

请问如何让Entry填充HorizontalStackLayout?


解决方案

要让Entry填充HorizontalStackLayout,需完成以下关键修改:

  1. 调整Entry的布局选项:将Entry的HorizontalOptions替换为LayoutOptions.FillAndExpand。LayoutOptions.Fill仅会让控件适配自身内容后填充,不会主动扩展占据剩余空间;而FillAndExpand会让控件抢占布局中除固定尺寸元素(如搜索按钮)外的所有剩余水平空间。
  2. 确认Grid列配置:确保Grid的第二列(值列)宽度设置为GridLength.Star,这样HorizontalStackLayout才能获得足够的可用空间来分配给内部控件。

修改后的核心代码

1. 更新Entry的布局设置

//IF THIS IS  A TEXT FIELD
if (cv.GetType() == typeof(Entry)) 
{ 
    var entry = (Entry)cv;
    entry.HorizontalOptions = LayoutOptions.FillAndExpand; // 替换原Fill设置
}

2. 补充Grid列定义(若未配置)

// 在创建Grid时添加列规则
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); // 标题列自适应宽度
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Star }); // 值列占剩余全部空间

其余代码保持不变即可,修改后Entry会自动填充HorizontalStackLayout中除搜索按钮外的所有可用水平空间,达到预期的填充效果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:44:53