我有一个具有HasUnevenRows = true的ListView。
我将ItemSource绑定到ObservableCollection。
此Collection用一些行填充ListViews。每行都有不同的高度,因为行与行之间的文本是不同的。
我想知道是否可以知道每一行的高度。
谢谢 亚历山德罗
IEnumerable<PropertyInfo> pInfos = (ListViewPrivacy as ItemsView<Cell>).GetType().GetRuntimeProperties();
var templatedItems = pInfos.FirstOrDefault(info => info.Name == "TemplatedItems");
if (templatedItems != null)
{
var cells = templatedItems.GetValue(ListViewPrivacy);
foreach (ViewCell cell in cells as Xamarin.Forms.ITemplatedItemsList<Xamarin.Forms.Cell>)
{
if (cell.BindingContext != null)
{
System.Diagnostics.Debug.WriteLine("CellHeight = " + cell.Height + " - " + cell.RenderHeight + " " + cell.View.Height + " - " + cell.View.HeightRequest + " - " + cell.View.MinimumHeightRequest + " - " );
Grid grid = (Grid)cell.View;
System.Diagnostics.Debug.WriteLine("Height = " + grid.Height.ToString() + " - " + grid.HeightRequest + " - " + grid.MinimumHeightRequest);
}
}
}
我尝试过使用这样的代码,但每个属性中的值始终为“ -1”
答案 0 :(得分:1)
好的,我找到了解决方案。
<ViewCell>
<Grid
SizeChanged="ViewCell_SizeChanged"
这是ViewCell_SizeChanged:
double totalHeight = 0;
int counter = 0;
private void ViewCell_SizeChanged(object sender, EventArgs e)
{
if(sender is Grid)
{
Grid grid = (Grid)sender;
totalHeight += grid.Height;
totalHeight += grid.Margin.Top;
totalHeight += grid.Margin.Bottom;
if(++counter == ((MyViewModel)this.BindingContext).MyObservableCollection.Count)
Device.BeginInvokeOnMainThread(() => MyListView.HeightRequest = totalHeight);
}
}
当ViewCell充满数据时,将调整网格的大小,以便引发ViewCell_SizeChanged事件。在这里,我有当前的Grid.Height和Margin值。当我达到项目总数时,我在ListView中具有所有网格的确切高度
答案 1 :(得分:0)
我想根据 Alessandro 的回答分享我的解决方案,但使用 FlowListView。我需要设置FlowListView HeightRequest,因为列表后面有一个巨大的空白空间。
XAML
<flv:FlowListView
FlowColumnCount="1"
FlowItemsSource="{Binding Coverages}"
SeparatorVisibility="None"
VerticalScrollBarVisibility="Never"
x:Name="listConverages"
HasUnevenRows="True">
<flv:FlowListView.FlowColumnTemplate>
<DataTemplate>
<StackLayout
SizeChanged="StackLayout_SizeChanged">
</StackLayout>
</DataTemplate>
</flv:FlowListView.FlowColumnTemplate>
</flv:FlowListView>
背后的代码
private Dictionary<Guid, double> itemsHeight = new Dictionary<Guid, double>();
private void StackLayout_SizeChanged(object sender, EventArgs e)
{
StackLayout stackLayout = (StackLayout)sender;
if (!itemsHeight.ContainsKey(stackLayout.Id))
itemsHeight.Add(stackLayout.Id, stackLayout.Height);
else
itemsHeight[stackLayout.Id] = stackLayout.Height;
listConverages.HeightRequest = itemsHeight.Sum(x => x.Value);
}
注意:如果您有下边距或上边距,请在将项目添加到字典之前将它们添加到值中