![](/img/trans.png)
[英]How to adjust size of Horizontal ListView in Xamarin.Forms?
[英]Xamarin.Forms ListView size to content?
我有一个相当大的表单(主要适用于平板电脑),它有一个嵌套ScrollView
的TabbedPage
和一个包含许多控件的垂直StackPanel
。
我有一个包含几个单行项目的ListView
的情况很少,我需要它调整大小以适应内容。
我想摆脱它的滚动条,但无论如何我不希望它占用比其项目所需空间更多的空间。
有没有一种方法(甚至是一种丑陋的方法)无需编写渲染器 x3 平台即可实现?
这是一个伪描述我的树:
<ContentPage>
<MasterDetailPage>
<MasterDetailPage.Detail>
<TabbedPage>
<ContentPage>
<ScrollView>
<StackPanel>
<!-- many controls-->
<ListView>
渲染时,在ListView
之后有一个巨大的差距。 我怎样才能避免这种情况?
我试着摆弄VerticalOptions
和HeightRequest
,但没有一个有效。
我正在寻找一种动态方式(最好没有继承)来实现这一点而不涉及自定义渲染器。
根据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;
}
}
特别是当您的项目数量很少并且不需要滚动时,只需使用 bindableLayout。 https:\/\/docs.microsoft.com\/en-us\/xamarin\/xamarin-forms\/user-interface\/layouts\/bindable-layouts<\/a>这总是完全按照大小呈现! 如果您有复杂的项目,并且有交互,那么这些项目非常好。
" 这里的大多数答案都有正确的想法,但似乎不适用于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.