MAUI实战 - MAUI基础 - MAUI基础练习
.NET MAUI设置Listview的子项高度
上一篇

从上一篇可以看到,MAUI的Listview控件的子项的高度,在Android系统上,跟Windows上不一致。这是什么原因导致的呢?怎样解决这个问题呢?请查看以下的代码(HtListviewPage.xaml):
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="HovertreeMaui.HtPages.HtListviewPage"
Title="Hovertree Listview">
<ScrollView>
<VerticalStackLayout>
<Label
Text="My Devices"
VerticalOptions="Center"
HorizontalOptions="Center" FontSize="32" FontAttributes="Bold" />

<ListView x:Name="htDeviceView" RowHeight="140" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Grid.Column="0"
Source="{Binding ImageUrl}"
Aspect="Center"
MinimumHeightRequest="500"
WidthRequest="180" />
<Label Grid.Column="1"
Text="{Binding Name}"
FontAttributes="Bold"
VerticalOptions="Start"/>
<Label Grid.Row="0"
Grid.Column="2"
Text="{Binding Company}"
FontAttributes="Italic"
VerticalOptions="Start" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

</VerticalStackLayout>
</ScrollView>
</ContentPage>
对应的C#程序(HtListviewPage.xaml.cs)代码:
using HovertreeMaui.HtModels;

namespace HovertreeMaui.HtPages;

public partial class HtListviewPage : ContentPage
{

List<HovertreeDevice> HtDevices = new List<HovertreeDevice>
{
new HovertreeDevice("笔记本电脑","Lenovo","16G内存","https://hovertree.com/hvtimg/201512/agagq0or_l.jpg"),
new HovertreeDevice("电风吹","Midea","星夜蓝","https://hovertree.com/hvtimg/201601/thbniyjx_l.png"),
// ...etc.,... 何问起
new HovertreeDevice("移动硬盘","西部数码","1TB","https://hovertree.com/hvtimg/201512/vt1tf0xl_l.jpg"),
new HovertreeDevice("移动硬盘","西部数码","1TB","https://hovertree.com/hvtimg/201512/vt1tf0xl_l.jpg"),
new HovertreeDevice("电脑键盘","Lenovo","2.4G无线连接","https://hovertree.com/hvtimg/bjafjd/iofopnro_l.png")
};
public HtListviewPage()
{
InitializeComponent();

this.htDeviceView.ItemsSource = HtDevices;
htDeviceView.ItemTapped += HtDeviceView_ItemTapped;

}

private async void HtDeviceView_ItemTapped(object sender, ItemTappedEventArgs e)
{
await DisplayAlert("HovertreeTips",((HovertreeDevice)( e.Item)).Details, "OK");
}
}
在Android系统上运行该代码,效果如下图:

从效果可以发现,Android系统上,列表的子项的高度已经与Windows系统上的一致。在代码中,发现设置了Listview的RowHeight="140"。所以Listview的RowHeight的设置可以解决安卓系统上行高的问题。
收藏 列表

评论: