Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

c# - How to set ListView to Start showing the last Item instead in Xamarin Forms?

I have a list of Items being handled by the ListView. By default, the ListView shows the from start to bottom (scrolling).

How do I set the ListView to start at the bottom instead?

Usage: Chat Messages View - Wherein I need to show the last message of the chat and scroll to that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use ScrollTo in a ListView to scroll to a any position you set. You need to overwrite the OnAppearing method. This is an example for scrolling to the end of the ListView ViewModel.Messages:

protected override void OnAppearing()
    {
        base.OnAppearing();

        ViewModel.RefreshScrollDown = () => {
            if (ViewModel.Messages.Count > 0) {
                Device.BeginInvokeOnMainThread (() => {

                    ListViewMessages.ScrollTo (ViewModel.Messages [ViewModel.Messages.Count - 1], ScrollToPosition.End, true);
                });
            }
        };
    }

Then just call RefreshScrollDown (which is System.Action) every time you need to scroll down, e.g. when you receive a new message or when you load the chats.

RefreshScrollDown in ViewModel:

public System.Action RefreshScrollDown;

You can get your ViewModel in code behind like this:

private MessagePhonePageViewModel ViewModel {
    get { return BindingContext as MessagePhonePageViewModel;}
}

NOTE: There is a bug when using a fixed ListView height. When changing the HeightRequest, ScrollTo still uses the original height of the list to calculate where it scrolls to. The original height is not updated when you change the value in HeightRequest. To fix this issue:

 protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            if (e.PropertyName == Xamarin.Forms.ListView.HeightRequestProperty.PropertyName)
            {
                Control.LayoutParameters.Height =(int)(sender as Xamarin.Forms.ListView).HeightRequest;
                Control.RequestLayout();

            }
        }  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...