如何将 ListView 设置为开始在 Xamarin Forms 中显示最后一个项目? [英] How to set ListView to Start showing the last Item instead in Xamarin Forms?
问题描述
我有一个 ListView 正在处理的项目列表.默认情况下,ListView 显示从开始到底部(滚动).
I have a list of Items being handled by the ListView. By default, the ListView shows the from start to bottom (scrolling).
如何将 ListView 设置为从底部开始?
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.
推荐答案
您可以在 ListView
中使用 ScrollTo
滚动到您设置的任何位置.您需要覆盖 OnAppearing
方法.这是滚动到 ListView
ViewModel.Messages 末尾的示例:
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);
});
}
};
}
然后在每次需要向下滚动时调用 RefreshScrollDown
(即 System.Action
),例如当您收到新消息或加载聊天时.
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.
ViewModel 中的RefreshScrollDown:
public System.Action RefreshScrollDown;
您可以像这样在代码中隐藏您的 ViewModel:
private MessagePhonePageViewModel ViewModel {
get { return BindingContext as MessagePhonePageViewModel;}
}
<小时>
注意:使用固定的 ListView
高度时存在一个错误.在更改HeightRequest
时,ScrollTo 仍然使用列表的原始高度来计算它滚动到的位置.当您更改 HeightRequest
中的值时,原始高度不会更新.要解决此问题:
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();
}
}
这篇关于如何将 ListView 设置为开始在 Xamarin Forms 中显示最后一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!