简体   繁体   English

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

[英]How to show and hide a StackLayout based on ListView scroll direction in Xamarin.Forms?

I have a screen with a ListView that shows a collection of comments. 我有一个带有ListView的屏幕,其中显示了评论的集合。 Also, I have a StackLayout overlapping the end of the ListView , which has an Entry and a Button to add a new comment. 另外,我还有一个StackLayoutListView的末尾重叠,后者有一个Entry和一个Button以添加新的注释。

I want to hide/show this StackLayout depending on the ListView scrolling direction: 我想根据ListView滚动方向隐藏/显示此StackLayout

  • If the user scrolls down -> hide the StackLayout . 如果用户向下滚动->隐藏StackLayout
  • If the user scrolls up -> show the StackLayout . 如果用户向上滚动->显示StackLayout

Anyone knows a way to accomplish that behavior? 任何人都知道一种完成该行为的方法吗?

Thanks in advance! 提前致谢!

Xamarin.Forms ListView provides an OnItemAppearing event you can subscribe to. Xamarin.Forms ListView提供了您可以订阅的OnItemAppearing事件。 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;
    }
}

EDIT: Flickering is really due to ListView being resized when the StackLayout shows and hides, so make sure that the ListView is not getting resized. 编辑:闪烁实际上是由于StackLayout显示和隐藏时ListView的大小已被调整,因此请确保ListView不会被调整大小。 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, eg: 也许将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>

With the above, the flickering no longer occurs. 通过以上操作,不再发生闪烁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM