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

雨燕双飞 提交于 2021-02-10 06:40:57

问题


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.

I want to hide/show this StackLayout depending on the ListView scrolling direction:

  • If the user scrolls down -> hide the StackLayout.
  • If the user scrolls up -> show the StackLayout.

Anyone knows a way to accomplish that behavior?

Thanks in advance!


回答1:


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;
    }
}

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. 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.



来源:https://stackoverflow.com/questions/54115536/how-to-show-and-hide-a-stacklayout-based-on-listview-scroll-direction-in-xamarin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!