You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何我的ListView仅显示一个条目?RecentLinks集合含多项却仅展示一项

嘿,我之前在做Xamarin.Forms项目时刚好踩过这个嵌套ListView的坑!你说RecentLinks明明有多个条目但只显示一个,大概率是布局计算的问题,给你几个解决思路:

1. 给内层ListView开启自适应行高

默认情况下,ListView的行高是固定的,如果你没开启Uneven Rows,它可能只会渲染第一行的高度,后面的条目直接被隐藏了。给内层的ListView加上HasUnevenRows="True"属性,让它根据内容自动调整行高:

<ListView ItemsSource="{Binding RecentLinks}" HasUnevenRows="True">
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell>
        <Label Text="{Binding Title}" FontSize="Micro" />
        <!-- 你的其他控件 -->
      </ViewCell>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

2. 手动指定内层ListView的高度(可选)

有时候即使开了自适应行高,外层ViewCell还是没法正确计算内层ListView的总高度,这时候可以试试绑定一个高度值。比如写个简单的Converter,根据RecentLinks的数量来计算总高度:

// 示例Converter:每个条目占40高度,可根据你的实际情况调整
public class CountToHeightConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is int count)
        {
            return count * 40;
        }
        return 0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

然后在XAML里引用并绑定:

<!-- 先在资源里声明Converter -->
<ContentPage.Resources>
  <local:CountToHeightConverter x:Key="CountToHeightConverter" />
</ContentPage.Resources>

<!-- 内层ListView绑定高度 -->
<ListView ItemsSource="{Binding RecentLinks}" 
          HasUnevenRows="True"
          HeightRequest="{Binding RecentLinks.Count, Converter={StaticResource CountToHeightConverter}}">
  <!-- 模板内容不变 -->
</ListView>

3. 更推荐:用BindableLayout替代嵌套ListView

其实官方并不推荐嵌套ListView,不仅性能差,布局问题也多。你可以用BindableLayout来替换内层的ListView,它会自动计算所有子项的高度,完全不用手动调整:

<ListView ItemsSource="{Binding Subscriptions}" HasUnevenRows="True">
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell>
        <StackLayout Orientation="Horizontal">
          <!-- 用BindableLayout展示RecentLinks列表 -->
          <StackLayout BindableLayout.ItemsSource="{Binding RecentLinks}">
            <BindableLayout.ItemTemplate>
              <DataTemplate>
                <Label Text="{Binding Title}" FontSize="Micro" />
                <!-- 你的其他控件 -->
              </DataTemplate>
            </BindableLayout.ItemTemplate>
          </StackLayout>
        </StackLayout>
      </ViewCell>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

这个方案不仅能解决你现在的显示问题,还能提升列表的滚动性能,建议优先试试这个!

内容的提问来源于stack exchange,提问作者Scott Nimrod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:39:20