如何在 Xamarin.Forms 中显示和隐藏基于 ListView 滚动方向的 StackLayout?
我有一个带有 ListView
的屏幕,它显示了一组评论.另外,我有一个 StackLayout
与 ListView
的末尾重叠,它有一个 Entry
和一个 Button
要添加一条新评论.
I have a screen with a ListView
that shows a collection of comments. Also, I have a StackLayout
overlapping the end of the ListView
, which has an Entry
and a Button
to add a new comment.
我想根据 ListView
滚动方向隐藏/显示这个 StackLayout
:
I want to hide/show this StackLayout
depending on the ListView
scrolling direction:
- 如果用户向下滚动 -> 隐藏
StackLayout
. - 如果用户向上滚动 -> 显示
StackLayout
.
有人知道实现这种行为的方法吗?
Anyone knows a way to accomplish that behavior?
提前致谢!
Xamarin.Forms ListView
提供了可以订阅的 OnItemAppearing
事件.有了这个,您可以通过查找出现的项目的索引并将其与最后出现的项目进行比较来跟踪滚动方向.尝试这样的事情:
Xamarin.Forms ListView
provides an OnItemAppearing
event you can subscribe to. With this you can track your scroll direction by finding the index of the item that appeared and comparing it to the last item that appeared. Try something like this:
public partial class MainPage : ContentPage
{
public ObservableCollection<MyItemType> Items { get; set; } = new ObservableCollection<MyItemType>();
int lastItemIndex;
int currentItemIndex;
public MainPage()
{
...
listView.ItemAppearing += ListView_ItemAppearing;
}
void ListView_ItemAppearing(object sender, ItemVisibilityEventArgs e)
{
MyItemType item = e.Item as MyItemType;
currentItemIndex = Items.IndexOf(item);
if (currentItemIndex > lastItemIndex)
{
stackLayout.IsVisible = false;
}
else
{
stackLayout.IsVisible = true;
}
lastItemIndex = currentItemIndex;
}
}
闪烁实际上是由于 ListView
在 StackLayout
显示和隐藏时调整了大小,因此请确保 ListView
没有调整大小.也许将 ListView 和 StackLayout 放在网格中,以便在显示和隐藏 StackLayout
时 ListView
不会调整大小,例如:
Flickering is really due to ListView
being resized when the StackLayout
shows and hides, so make sure that the ListView
is not getting resized. Perhaps put the ListView and the StackLayout in a grid so that when you show and hide the StackLayout
the ListView
does not get resized, e.g.:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="35" />
</Grid.RowDefinitions>
<ListView x:Name="listView"
ItemsSource="{Binding Items}"
Grid.Row="0">
<ListView.ItemTemplate>
...
</ListView.ItemTemplate>
</ListView>
<StackLayout x:Name="stackLayout"
Grid.Row="1">
...
</StackLayout>
</Grid>
使用上述方法,不再出现闪烁.
With the above, the flickering no longer occurs.