There is more space than I need in ListView

前端 未结 5 1237
生来不讨喜
生来不讨喜 2021-01-19 19:56

I\'m using StackLayout and ListView to show some part of a view, but the ListView takes more space than I need, and leaves a blank space between the last row of the list and

5条回答
  •  孤独总比滥情好
    2021-01-19 20:25

    I had issues with Yehor Hromadskyi's solution.

    • First off IEnumerable doesn't have a Count method. It must first be cast to an IEnumerable
    • Second, if you don't set RowHeight you then the whole list collapses and you have the opposite problem.

    Here are the changes to the code to fix those issues

    public class ListViewHeightBehavior : Behavior
    {
        private ListView _listView;
    
        public static readonly BindableProperty ExtraSpaceProperty =
            BindableProperty.Create(nameof(ExtraSpace),
                                    typeof(double),
                                    typeof(ListViewHeightBehavior),
                                    0d);
    
        public static readonly BindableProperty DefaultRowHeightProperty =
            BindableProperty.Create(nameof(DefaultRowHeight),
                              typeof(int),
                              typeof(ListViewHeightBehavior),
                              40);
    
        public int DefaultRowHeight
        {
            get => (int)GetValue(DefaultRowHeightProperty);
            set => SetValue(DefaultRowHeightProperty, value);
        }
        public double ExtraSpace
        {
            get { return (double)GetValue(ExtraSpaceProperty); }
            set { SetValue(ExtraSpaceProperty, value); }
        }
    
        protected override void OnAttachedTo(ListView bindable)
        {
            base.OnAttachedTo(bindable);
    
            _listView = bindable;
            _listView.PropertyChanged += (s, args) =>
            {
                var count = _listView.ItemsSource?.Cast()?.Count();
                if (args.PropertyName == nameof(_listView.ItemsSource)
                        && count.HasValue
                        && count.Value > 0)
                {
                    int rowHeight = _listView.RowHeight > 0 ? _listView.RowHeight : DefaultRowHeight;
                    _listView.HeightRequest = rowHeight * count.Value + ExtraSpace;
                }
            };
        }
    }
    
        

    提交回复
    热议问题