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
相关产品推荐
相关产品推荐

