简体   繁体   中英

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

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, eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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