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.