I have ListView
with binding ItemsSource
(it is ObservableRangeCollection
). I want to automatically scroll down ListView
when page is appearing. What should I do?
It is View
:
<ListView
x:Name="ListAdd"
ItemsSource="{Binding AddNewFlashcard}"
(...)
>
<ListView.Behaviors>
<(...)>
</ListView.Behaviors>
<ListView.ItemTemplate>
<DataTemplate x:DataType="models:Flashcard">
<ViewCell>
<Grid Padding="10">
<Frame CornerRadius="20" HasShadow="True">
<StackLayout VerticalOptions="Center">
<Label FontSize="Large"
Text="{Binding Word}"
VerticalOptions="Center"/>
<Label Text="{Binding Sentence}"
VerticalOptions="Center"/>
</StackLayout>
</Frame>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
It is ViewModel:
public ObservableRangeCollection<Flashcard> AddNewFlashcard { get; set; }
public NewFlashcardVM()
{
Refresh();
AddNewFlashcard = new ObservableRangeCollection<Flashcard>();
}
public async void Refresh()
{
IsBusy = true;
var flashcards = await FlashcardService.GetFlashcard();
AddNewFlashcard.AddRange(flashcards);
IsBusy = false;
}
CodePudding user response:
You can achieve the effect you want by calling the ScrollTo method in the ListView.
I wrote a small example for your reference.
Here is the xaml code:
<StackLayout>
<Frame HeightRequest="100">
<ListView x:Name="mytest" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text="{Binding .}"></Label>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Frame>
</StackLayout>
Here is the background code(When the data is loaded, call the ScrollTo method of ListView in the OnAppearing method):
public partial class MainPage : ContentPage
{
ObservableRangeCollection<string> myList;
public MainPage()
{
InitializeComponent();
myList = new ObservableRangeCollection<string>();
myList.Add("aaa");
myList.Add("aaa");
myList.Add("aaa");
myList.Add("aaa");
myList.Add("aaa");
myList.Add("aaa");
myList.Add("bbb");
mytest.ItemsSource = myList;
BindingContext = this;
}
protected override void OnAppearing()
{
base.OnAppearing();
mytest.ScrollTo(myList[myList.Count-1], ScrollToPosition.End,false);
}
}
If you change the last parameter of ScrollTo to true, a sliding animation will occur.