今天打算使用 ListView 搭配 ViewCell 展示一份文本列表时,遇到了一个问题,代码如下:
<ListView x:Name="listView"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <StackLayout Padding="20"> <Label Text="{Binding Text}" /> </StackLayout> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>
ViewCell 中使用了一个 StackLayout 并对其设置了 Padding,但是实际运行后发现 ViewCell 的高度是统一且固定的,超出的区域会被直接截掉。虽然可以直接对 ViewCell 设置高度,但这显然不符合我的需求。经过搜索,我在微软的文档中发现了其实控制 ViewCell 为自动高度与否其实是在 ListView 中设置。
获取或设置一个布尔值,该值指示此 ListView 元素是否具有不均匀的行。
属性值
ListView.HasUnevenRows 属性 (Xamarin.Forms) | Microsoft Docs
Boolean
如果此 ListView 控件具有不均匀的行为 true,否则为 false。
看到这里我就豁然开朗了,不过感觉这个设定有点绕?加上该属性后 ViewCell 成功如预期显示。
<ListView x:Name="listView" HasUnevenRows="True"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <StackLayout Padding="20"> <Label Text="{Binding Text}" /> </StackLayout> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>