簡體   English   中英

Xamarin.Forms ListView 大小到內容?

[英]Xamarin.Forms ListView size to content?

我有一個相當大的表單(主要適用於平板電腦),它有一個嵌套ScrollViewTabbedPage和一個包含許多控件的垂直StackPanel

我有一個包含幾個單行項目的ListView的情況很少,我需要它調整大小以適應內容。
我想擺脫它的滾動條,但無論如何我不希望它占用比其項目所需空間更多的空間。
有沒有一種方法(甚至是一種丑陋的方法)無需編寫渲染器 x3 平台即可實現?

這是一個偽描述我的樹:

<ContentPage>
  <MasterDetailPage>
    <MasterDetailPage.Detail>
      <TabbedPage>
        <ContentPage>
          <ScrollView>
            <StackPanel>
              <!-- many controls-->
              <ListView>

渲染時,在ListView之后有一個巨大的差距。 我怎樣才能避免這種情況?

我試着擺弄VerticalOptionsHeightRequest ,但沒有一個有效。

我正在尋找一種動態方式(最好沒有繼承)來實現這一點而不涉及自定義渲染器。

根據Lutaaya的回答 ,我做了一個自動執行此操作的行為,確定並設置行高( Gist )。

行為:

namespace Xamarin.Forms
{
  using System;
  using System.Linq;
  public class AutoSizeBehavior : Behavior<ListView>
  {
    ListView _ListView;
    ITemplatedItemsView<Cell> 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;
    }
  }
}

用法:

<ContentPage xmlns:xf="clr-namespace:Xamarin.Forms">
  <ListView>
    <ListView.Behaviors>
      <xf:AutoSizeBehavior />

確定假設您的ListView填充了NewsFeeds,讓我們使用ObservableCollection來包含我們的數據以填充ListView,如下所示:

XAML代碼:

<ListView x:Name="newslist"/>

C#代碼

ObservableCollection <News> trends = new ObservableCollection<News>();

然后將趨勢列表分配給ListView:

newslist.ItemSource = trends;

然后,我們在ListView和數據上做了一些邏輯,以便ListView包裝數據, 隨着數據的增加,ListView也增加了,反之亦然

int i = trends.Count;
int heightRowList = 90;
i = (i * heightRowList);
newslist.HeightRequest = i;

因此完整的代碼是:

ObservableCollection <News> trends = new ObservableCollection<News>();
newslist.ItemSource = trends;
int i = trends.Count;
int heightRowList = 90;
i = (i * heightRowList);
newslist.HeightRequest = i;

希望能幫助到你 。

我可能在這里過分簡化了一些事情,但只是向ListView添加了HasUnevenRows="True"

我可以創建一個事件處理程序,它考慮到ListView單元格的大小變化。 這是它:

    <ListView ItemsSource="{Binding Items}"
         VerticalOptions="Start"
         HasUnevenRows="true"
         CachingStrategy="RecycleElement"
         SelectionMode="None" 
         SizeChanged="ListView_OnSizeChanged">
               <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell >
                           <Frame Padding="10,0" SizeChanged="VisualElement_OnSizeChanged">

可以通過Grid,StackLayout等更改框架xaml.cs:

        static readonly Dictionary<ListView, Dictionary<VisualElement, int>> _listViewHeightDictionary = new Dictionary<ListView, Dictionary<VisualElement, int>>();

    private void VisualElement_OnSizeChanged(object sender, EventArgs e)
    {
        var frame = (VisualElement) sender;
        var listView = (ListView)frame.Parent.Parent;
        var height = (int) frame.Measure(1000, 1000, MeasureFlags.IncludeMargins).Minimum.Height;
        if (!_listViewHeightDictionary.ContainsKey(listView))
        {
            _listViewHeightDictionary[listView] = new Dictionary<VisualElement, int>();
        }
        if (!_listViewHeightDictionary[listView].TryGetValue(frame, out var oldHeight) || oldHeight != height)
        {
            _listViewHeightDictionary[listView][frame] = height;
            var fullHeight = _listViewHeightDictionary[listView].Values.Sum();
            if ((int) listView.HeightRequest != fullHeight 
                && listView.ItemsSource.Cast<object>().Count() == _listViewHeightDictionary[listView].Count
                )
            {
                listView.HeightRequest = fullHeight;
                listView.Layout(new Rectangle(listView.X, listView.Y, listView.Width, fullHeight));
            }
        }
    }

    private void ListView_OnSizeChanged(object sender, EventArgs e)
    {
        var listView = (ListView)sender;
        if (listView.ItemsSource == null || listView.ItemsSource.Cast<object>().Count() == 0)
        {
            listView.HeightRequest = 0;
        }
    }

當Frame正在顯示(ListView.ItemTemplate正在應用)時,幀的大小會發生變化。 我們通過Measure()方法獲取它的實際高度並將其放入Dictionary中,它了解當前的ListView並保持Frame的高度。 當顯示最后一幀時,我們總結所有高度。 如果沒有項目,ListView_OnSizeChanged()將listView.HeightRequest設置為0。

我知道這是一個舊線程,但到目前為止我找不到更好的解決方案 - 兩年多后:-(

我正在使用 Xamarin.Forms v5.0.0.2244。 實現並應用了 Shimmy 在上面的“用法:”中建議的行為,但是,AppearanceChanged 是針對每個列表視圖項執行的,而不是針對列表視圖本身。 因此,當在 UpdateHeight 中測量高度時,它測量單個項目的高度,並將列表視圖的高度設置為該值 - 這是不正確的。 這種行為似乎是合理的,因為它附加到 ItemAppearing 和 ItemDisappering 事件。

然而,按照 Shimmy 的想法,這里有一個改進的(但遠非完美的)實現。 這個想法是處理項目外觀,測量這些項目並計算它們的總和,在我們進行時更新父列表視圖的高度。

對我來說,初始高度計算不能正常工作,好像有些項目不會出現,因此不計算在內。 我希望有人可以改進它,或者指出更好的解決方案:

internal class ListViewAutoShrinkBehavior : Behavior<ListView>
{
    ListView _listView;
    double _height = 0;

    protected override void OnAttachedTo(ListView listview)
    {
        listview.ItemAppearing += OnItemAppearing;
        listview.ItemDisappearing += OnItemDisappearing;
        _listView = listview;
    }

    protected override void OnDetachingFrom(ListView listview)
    {
        listview.ItemAppearing -= OnItemAppearing;
        listview.ItemDisappearing -= OnItemDisappearing;
        _listView = null;
    }

    void OnItemAppearing(object sender, ItemVisibilityEventArgs e)
    {
        _height += MeasureRowHeight(e.Item);
        SetHeight(_height);
    }

    void OnItemDisappearing(object sender, ItemVisibilityEventArgs e)
    {
        _height -= MeasureRowHeight(e.Item);
        SetHeight(_height);
    }

    int MeasureRowHeight(object item)
    {
        var template = _listView.ItemTemplate;
        var cell = (Cell)template.CreateContent();
        cell.BindingContext = item;
        double height = cell.RenderHeight;
        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;
    }
}

這里的大多數答案都有正確的想法,但似乎不適用於ViewCell元素。 這是我能想到的最有效的解決方案:

public class AutoSizeBehavior : Behavior<ListView>
{
    ListView _listView;
    VisualElement _parent;

    ITemplatedItemsList<Cell> _itemsList;
    Dictionary<int, double> _cells = new Dictionary<int, double>();
    Dictionary<VisualElement, int> _elMap = new Dictionary<VisualElement, int>();

    double _parentHeight;
    double _contentHeight;

    protected override void OnAttachedTo(ListView bindable)
    {
        bindable.ItemAppearing += HandleItemAppearing;

        _listView = bindable;
        _itemsList = ((ITemplatedItemsView<Cell>)_listView).TemplatedItems;

        if (_listView.Parent is VisualElement parent)
        {
            AttachToParent(parent);
        }
        else
        {
            _listView.PropertyChanged += HandleListViewPropertyChanged;
        }

        for (int i = 0; i < _itemsList.Count; i++)
            UpdateItemHeight(i);
    }

    protected override void OnDetachingFrom(ListView bindable)
    {
        _listView.ItemAppearing -= HandleItemAppearing;
        _listView.PropertyChanged -= HandleListViewPropertyChanged;

        for (int i = 0; i < _itemsList.Count; i++)
        {
            var cell = _itemsList[i];
            cell.PropertyChanged -= HandleCellPropertyChanged;
        }

        foreach (var pair in _elMap)
        {
            var el = pair.Key;
            el.SizeChanged -= HandleCellSizeChanged;
        }

        if (_parent != null)
            _parent.SizeChanged -= HandleParentSizeChanged;

        _elMap.Clear();
        _cells.Clear();

        _cells = null;
        _itemsList = null;
        _listView = null;
        _parent = null;
        _parentHeight = _contentHeight = -1;
    }

    #region Handlers
    private void HandleItemAppearing(object sender, ItemVisibilityEventArgs e)
    {
        UpdateItemHeight(e.ItemIndex);
    }

    private void HandleListViewPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == nameof(ListView.Parent))
        {
            if (_listView.Parent is VisualElement parent)
            {
                AttachToParent(parent);
                _listView.PropertyChanged -= HandleListViewPropertyChanged;
            }
        }
    }

    private void HandleParentSizeChanged(object sender, EventArgs e)
    {
        if (_parent == null) return;

        _parentHeight = _parent.Height;
        AdjustListHeight();
    }

    private void HandleCellPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (!(sender is Cell cell)) return;

        if (e.PropertyName == nameof(Cell.RenderHeight))
        {
            int index = _itemsList.IndexOf(cell);

            if (index < 0)
                return;

            UpdateItemHeight(index);
        }
    }

    private void HandleCellSizeChanged(object sender, EventArgs e)
    {
        if (!(sender is VisualElement el)) return;

        if (_elMap.TryGetValue(el, out int index))
            UpdateItemHeight(index);
    }
    #endregion

    private void AttachToParent(VisualElement parent)
    {
        _parent = parent;
        _parentHeight = _parent.Height;
        _parent.SizeChanged += HandleParentSizeChanged;
    }

    private void UpdateItemHeight(int index)
    {
        Cell cell = _itemsList[index];
        double newHeight;

        if (!_cells.TryGetValue(index, out double oldHeight))
        {
            oldHeight = 0.0;
            _cells[index] = oldHeight;

            if (cell is ViewCell viewCell)
            {
                _elMap[viewCell.View] = index;
                viewCell.View.SizeChanged += HandleCellSizeChanged;
            }
            else
            {
                cell.PropertyChanged += HandleCellPropertyChanged;
            }
        }

        if (cell is ViewCell vCell)
        {
            newHeight = vCell.View.Height;
        }
        else
        {
            newHeight = cell.RenderHeight;
        }

        if (newHeight >= 0)
        {
            double delta = newHeight - oldHeight;
            if (delta == 0) return;

            _cells[index] = newHeight;

            _contentHeight += delta;
            AdjustListHeight();
        }
    }

    private void AdjustListHeight()
    {
        if (_contentHeight > 0 && _contentHeight < _parentHeight)
        {
            _listView.HeightRequest = _contentHeight;
        }
        else if (_parentHeight >= 0)
        {
            if (_listView.HeightRequest != _parentHeight)
                _listView.HeightRequest = _parentHeight;
        }
    }
}

AutoSizeBehavior的這種實現可以很好地調整大小並自行清理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM