具有分组的 Xamarin 列表视图不会滚动



我正在开发我的第一个 Xamarin 应用程序。我想制作一个带有分组的列表视图,它成功了。我唯一的问题是它不会滚动。我在另一个页面上的其他列表视图滚动没有问题,但我的分组列表视图不会这样做。我在Android模拟器上和在我的Android手机上都尝试过(我没有Macbook或iOS上测试的东西(,它不会在任何一个上滚动。我查了一下,但很多人把列表视图放在滚动视图中,我没有这样做。

这是我的 XAML 代码:

<StackLayout Margin="10" Orientation="Vertical">
<Label Text="{Binding Title}" FontAttributes="Bold" 
FontSize="20" HorizontalOptions="CenterAndExpand" />
<Label Text="{Binding Subtitle}" FontAttributes="Italic" 
FontSize="15" HorizontalOptions="CenterAndExpand" />
<ListView HasUnevenRows="True" SeparatorColor="Accent" 
VerticalOptions="FillAndExpand" IsEnabled="False"
IsGroupingEnabled="True" GroupDisplayBinding="{Binding Key}" 
ItemsSource="{Binding ScansGroup}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Spacing="4">
<StackLayout Orientation="Horizontal" Margin="10,7,10,1">
<Label Text="{Binding Location, StringFormat='{0}'}" 
FontAttributes="Bold" FontSize="16" />
<Label Text="{Binding DateTime, StringFormat='{0:dd/MM/y HH:mm}'}"
HorizontalOptions="EndAndExpand" />
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding ElapsedTimeOnLocation}" 
HorizontalOptions="Start"
Margin="10,0,10,7" />
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>

我把它放在 MVVM 结构中,我用从这里得到的 MVVM 助手进行的分组 https://channel9.msdn.com/Shows/XamarinShow/The-Xamarin-Show-12-MVVM-Helpers. 我的代码用于分组如下:

public ObservableRangeCollection<Grouping<string, ScanViewModel>> ScansGroup { get; } = 
new ObservableRangeCollection<Grouping<string, ScanViewModel>>();
void Group()
{
var grouped = from scan in Scans
group scan by scan.Day into scanGroup
select new Grouping<string, ScanViewModel>(scanGroup.Key, scanGroup);
ScansGroup.ReplaceRange(grouped);
}

分组和列表都完美显示。唯一的问题是 我无法滚动。有人可以帮助我吗?

我已经想通了。您的分组没有错。在代码中,您将IsEnabled="False"设置为ListView。它使列表视图的滚动能力仅在您从ListView内的启用项目拖动时才能处理,即使如此,滚动就像被贬低并且用户体验非常糟糕。

只需像这样设置您的ListView

<ListView HasUnevenRows="True" 
SeparatorColor="Accent" 
VerticalOptions="FillAndExpand" 
IsEnabled="True"
IsGroupingEnabled="True" 
GroupDisplayBinding="{Binding Key}" 
ItemsSource="{Binding ScansGroup}">
...
</ListView>

我不能告诉你它是否被设计成这样,或者它是否是一个错误,但它是你问题的原因。

您这样做很可能是为了处理一些不需要的行为。如果是这样,请告诉我们您对这个IsEnabled="False"的具体意图,然后我们将能够为您提供帮助。

我希望它对你有所帮助。

您没有为组添加模板。在<ListView>中添加此内容

<ListView.GroupHeaderTemplate >
<DataTemplate >
<ViewCell Height="28" >
<Label Text="{Binding GroupName}" VerticalTextAlignment="Center" HorizontalOptions="Start" />
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>

此外,在代码折弯或 ViewModel 中,您需要绑定到列表中所需项的组类,例如:

public class GroupDetails : ObservableCollection<SomeItemsToShow>
{
public string GroupName { get; set; }
}

查看此示例以获取更多详细信息: https://xamarinhelp.com/xamarin-forms-listview-grouping/

最新更新