Behzad
Behzad

Reputation: 2190

Xamarin Forms ListView Scroll position - MVVM

I'm searching about this article for weeks!

UPDATE

Is controlling Listview scroll position in xamarin forms with MVVM pattern possible or not? getting and setting the scroll position of listview.

There are some answers like implementing event aggregation or using messaging or ... . Neither of them weren't operating for me. The messaging is not fully MVVM pattern way. The event aggregation didn't work even I'm using prism 7. There is no such a good example code or any nuget package.

Has anyone encountered this problem and solved it?

Upvotes: 0

Views: 3133

Answers (1)

Marzie Sangtarash
Marzie Sangtarash

Reputation: 159

CustomersViewModel

public ObservableCollection<Customer> Customers {get;set;}
public Func<Customer,Task> ScrollToCustomer {get;set;}
public DelegateCommand FindBestCustomer {get;set;} // For example    
FindBestCustomer = new DelegateCommand(async() => 
{ 
    Customer bestCustomer = Customers.Last(); // this is our logic in view model!
    await ScrollToCustomer(bestCustomer);
    // at this time, scroll is finished.
});

CustomersView.xaml

<StackLayout>
    <ListView x:Name="CustomersListView" ItemsSource={Binding Customers} />
    <Button Text="Go to last customer" Command="{Binding ScrollToLastCustomer}" /> // For example
</StackLayout>

CustomersView.xaml.cs

override OnBindingContextChanged()
{
    if(BindingContext is CustomersViewModel customersViewModel)
    {
        customersViewModel.ScrollToCustomer = customer => CustomersListView.ScrollTo(customer);
    }
}

Upvotes: 1

Related Questions