如何在 Xamarin.Forms 中显示和隐藏基于 ListView 滚动方向的 StackLayout?

Jua*_*ili 2 c# xamarin xamarin.forms

我有一个ListView显示评论集合的屏幕。另外,我有一个StackLayout重叠的结尾ListView,它有一个Entry和一个Button来添加新评论。

我想StackLayout根据ListView滚动方向隐藏/显示它:

  • 如果用户向下滚动 -> 隐藏StackLayout.
  • 如果用户向上滚动 -> 显示StackLayout.

有人知道实现这种行为的方法吗?

提前致谢!

jgo*_*SFT 5

Xamarin.FormsListView提供了一个OnItemAppearing可以订阅的事件。有了这个,您可以通过查找出现的项目的索引并将其与最后出现的项目进行比较来跟踪滚动方向。尝试这样的事情:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:闪烁实际上是由于ListView在StackLayout显示和隐藏时调整了大小,因此请确保ListView没有调整大小。也许把ListView控件和StackLayout在网格中,这样当你显示和隐藏StackLayout的ListView没有得到调整,例如:

<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>
Run Code Online (Sandbox Code Playgroud)

通过以上,不再发生闪烁。