Xamarin.Forms ListView size to content?

前端 未结 4 1850
星月不相逢
星月不相逢 2020-12-31 09:10

I have a pretty large form (adapted mainly for tablets), that has a TabbedPage nesting a ScrollView and a vertical StackPanel containi

4条回答
  •  天涯浪人
    2020-12-31 10:00

    Based on Lutaaya's answer, I made a behavior that automates this, determining and setting the row-height (Gist).

    Behavior:

    namespace Xamarin.Forms
    {
      using System;
      using System.Linq;
      public class AutoSizeBehavior : Behavior
      {
        ListView _ListView;
        ITemplatedItemsView Cells => _ListView;
    
        protected override void OnAttachedTo(ListView bindable)
        {
          bindable.ItemAppearing += AppearanceChanged;
          bindable.ItemDisappearing += AppearanceChanged;
          _ListView = bindable;
        }
    
        protected override void OnDetachingFrom(ListView bindable)
        {
          bindable.ItemAppearing -= AppearanceChanged;
          bindable.ItemDisappearing -= AppearanceChanged;
          _ListView = null;
        }
    
        void AppearanceChanged(object sender, ItemVisibilityEventArgs e) =>
          UpdateHeight(e.Item);
    
        void UpdateHeight(object item)
        {
          if (_ListView.HasUnevenRows)
          {
            double height;
            if ((height = _ListView.HeightRequest) == 
                (double)VisualElement.HeightRequestProperty.DefaultValue)
              height = 0;
    
            height += MeasureRowHeight(item);
            SetHeight(height);
          }
          else if (_ListView.RowHeight == (int)ListView.RowHeightProperty.DefaultValue)
          {
            var height = MeasureRowHeight(item);
            _ListView.RowHeight = height;
            SetHeight(height);
          }
        }
    
        int MeasureRowHeight(object item)
        {
          var template = _ListView.ItemTemplate;
          var cell = (Cell)template.CreateContent();
          cell.BindingContext = item;
          var height = cell.RenderHeight;
          var mod = height % 1;
          if (mod > 0)
            height = height - mod + 1;
          return (int)height;
        }
    
        void SetHeight(double height)
        {
          //TODO if header or footer is string etc.
          if (_ListView.Header is VisualElement header)
            height += header.Height;
          if (_ListView.Footer is VisualElement footer)
            height += footer.Height;
          _ListView.HeightRequest = height;
        }
      }
    }
    

    Usage:

    
      
        
          
    

提交回复
热议问题