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

Xamarin Forms中单元格间出现间隙的问题排查

自定义ViewCell中动态添加Grid导致单元格间隙过大

图片说明

右侧高亮为黑色的项内包含一个自定义视图。由于这个黑色自定义视图,每个View Cell之间出现了较大间隙。该黑色视图是在BindingContextChanged方法中添加的Grid控件。

以下是相关实现代码:

public partial class ShiftTemplate : ViewCell { 
    public ShiftTemplate() { 
        InitializeComponent(); 
    } 
} 

public class ShiftView : ContentView { 
    protected override void OnBindingContextChanged() { 
        base.OnBindingContextChanged(); 
        var model = BindingContext as StaffShiftViewModel; 
        var grid = new Grid(); 
        var shiftCount = 0; 
        var index = 0; 
        grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Star }); 
        grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Star }); 

        foreach (var shift in model.Shifts) { 
            grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }); 
            grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }); 
            grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto }); 

            var timeLabel = new Label { 
                Text = shift.Time, 
                VerticalTextAlignment = TextAlignment.Center, 
                HorizontalTextAlignment = TextAlignment.End 
            }; 

            var clockButton = new Button { 
                Text = shift.ClockStatus, 
                VerticalOptions = LayoutOptions.Center, 
                HorizontalOptions = LayoutOptions.Start, 
                Command = shift.OnClockingPopupCommand 
            }; 

            var binding = new Binding(); 
            binding.Source = shift; 
            binding.Path = nameof(shift.ClockStatus); 
            binding.Mode = BindingMode.OneWay; 
            clockButton.SetBinding(Button.TextProperty, binding); 

            var line = new BoxView { 
                HorizontalOptions = LayoutOptions.FillAndExpand, 
                VerticalOptions = LayoutOptions.Center, 
                HeightRequest = 1, 
                BackgroundColor = Color.Gray 
            }; 

            grid.Children.Add(timeLabel, 0, 1, shiftCount, shiftCount+1); 
            grid.Children.Add(clockButton, 1, 2, shiftCount, shiftCount+1); 
            index += 1; 

            if (index < model.Shifts.Count) 
                grid.Children.Add(line, 0, 2, shiftCount + 1, shiftCount + 2); 

            shiftCount+=2; 
        } 

        Content = grid; 
        ForceLayout(); 
    } 
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:30:52