简体   繁体   中英

ListView focus on the last item in the list? - Xamarin Forms

Could someone tell me how to keep the ListView focus always on the last list item? Following the example of a conversation in WhatsApp, where when we send a message, the message that has just arrived is always focused ... or any similar solution?

What I look for is whenever something is inserted in the ListView , instead of the Give the option to go up to view the items below, I would like it to be the other way around. Always displaying the last item on the screen.

I created an example where you have two elements, a list view and a buttom for adding new elements.

This is my XAML:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="4*" />
    </Grid.RowDefinitions>
    <ListView x:Name="ListView" />
    <Button
        Grid.Row="1"
        Clicked="Button_OnClicked"
        Text="Add animal" />
</Grid>

As you can see the button is very huge in order to show better the scroll.

In my Code-behind, I use ListView.ScrollTo method to scroll to the last added element, with animation:

public partial class MainPage : ContentPage
{
    private ObservableCollection<String> animals;
    private int _counter = 0;

    public MainPage()
    {
        InitializeComponent();
        animals = new ObservableCollection<string>(new List<string>{"dog","cat","fish","elephant","monkey"});
        ListView.ItemsSource = animals;
    }

    private void Button_OnClicked(object sender, EventArgs e)
    {
        var newElement = "new animal"+_counter;
        _counter++;
        animals.Add(newElement);
        ListView.ScrollTo(newElement, ScrollToPosition.End, true);
    }
}

I hope that this can help you.

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