I want to automatically scroll to the selected item in my collection view. Am using an ObservableCollection and am able to pre-select an item in my view. So I want it to appear on the screen to be seen incase the items are many.
So the view should automatically scroll to the selected item.
Code
public ObservableCollection WorkerFlockDetails { get; set; }
private WorkerFlock selectedFlock;
public WorkerFlock SelectedFlock
{
get => selectedFlock;
set
{
if (selectedFlock != value)
{
try
{
//Feed = selectedFlock.Feed_intake.ToString() " Kg";
selectedFlock = value;
}
catch
{
}
finally
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedFlock)));
}
}
}
}
This is where I initialize and pre-select
public HomeWorkerViewModel()
{
WorkerFlockDetails = new ObservableCollection<WorkerFlock>();
//populate the collection
Init();
SelectedFlock = WorkerFlockDetails.Skip(3).FirstOrDefault();
}
CodePudding user response:
You could use the code below and set the ScrollTo method in OnAppearing prior to the page becoming visable.
Xaml:
<CollectionView x:Name="collectionView"
ItemsSource="{Binding WorkerFlockDetails}"
ItemsLayout="HorizontalList"
SelectionMode="Single"
VerticalOptions="Start"
Margin="0,22,0,0"
HeightRequest="32"
SelectedItem="{Binding SelectedFlock, Mode=TwoWay}">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid>
<Label Text="{Binding Name}" Margin="20,0,20,0"
TextColor="#707070"
FontSize="20"></Label>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Code behind:
public partial class Page19 : ContentPage
{
public ObservableCollection<WorkerFlock> WorkerFlockDetails { get; set; }
public WorkerFlock SelectedFlock { get; set; }
public Page19()
{
InitializeComponent();
WorkerFlockDetails = new ObservableCollection<WorkerFlock>()
{
new WorkerFlock(){ Name="A"},
new WorkerFlock(){ Name="B"},
new WorkerFlock(){ Name="C"},
new WorkerFlock(){ Name="D"},
new WorkerFlock(){ Name="E"},
new WorkerFlock(){ Name="F"},
new WorkerFlock(){ Name="G"}
};
SelectedFlock = WorkerFlockDetails.Skip(3).FirstOrDefault();
this.BindingContext = this;
}
protected override void OnAppearing()
{
base.OnAppearing();
collectionView.ScrollTo(collectionView.SelectedItem, null, ScrollToPosition.Center, false);
}
}
public class WorkerFlock
{
public string Name { get; set; }
}
CodePudding user response:
You can use the .ScrollTo(); method on the CollectionView for this.