我需要一个像whatsapp聊天的ListView渲染器。
当新消息到来时,它会自动向下滚动。
如果有样品,请告诉我。
谢谢
发布于 2019-05-23 02:05:02
你不需要一个自定义的渲染器,你只需要使用一个ListView并添加一些逻辑来为你做滚动。
View.xaml文件:
<!-- Previous Implementation -->
<ListView x:Name="MessagesListView"
Grid.Row="0"
BackgroundColor="Transparent"
HasUnevenRows="True"
ItemTemplate="{StaticResource MessageTemplateSelector}"
ItemsSource="{Binding Messages}"
SelectionMode="None"
SeparatorVisibility="None" />
<!-- Remaining Implementation -->
x:Name
属性是重要的部分,您将在后面的代码中使用该名称。
现在是View.xaml.cs文件:
// Previous Implmentation
/// <summary>
/// Override of OnAppearing method. Fires as page is appearing.
/// Good place to set up event handlers.
/// </summary>
protected override void OnAppearing()
{
base.OnAppearing();
((INotifyCollectionChanged)MessagesListView.ItemsSource).CollectionChanged += OnListViewCollectionChanged;
}
/// <summary>
/// Override of OnDisappearing method. Fires as page is disappearing.
/// Good place to tear down event handlers.
/// </summary>
protected override void OnDisappearing()
{
base.OnDisappearing();
((INotifyCollectionChanged)MessagesListView.ItemsSource).CollectionChanged -= OnListViewCollectionChanged;
}
/// <summary>
/// Scrolls a the messages listview to the last item whenever
/// a new message is added to the collection.
/// </summary>
private void OnListViewCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
var myList = ((IEnumerable<Message>)MessagesListView.ItemsSource).ToList();
// Must be ran on main thread or Android chokes.
Device.BeginInvokeOnMainThread(async () =>
{
// For some reason Android requires a small delay or the scroll never happens.
await Task.Delay(50);
MessagesListView.ScrollTo(myList.Last(), ScrollToPosition.End, false);
});
}
// Remaining Implementation
基本上,只要ListView的ItemSource发生变化,就会触发一个事件。在这种情况下,您将滚动到列表的末尾。
发布于 2019-05-22 23:50:48
你不需要一个自定义渲染器来聊天,因为一个简单的ListView就足够了。
基本上,您将把ItemsSource属性绑定到一个ObservableCollection,这样当添加新消息时,它将自动出现在列表视图中。
此外,如果您认为用户不需要/必须立即查看大量历史聊天消息,则可能需要使用无限滚动技术,例如https://www.youtube.com/watch?v=DG5Asglf0vU
要滚动到最后一条消息:
Device.BeginInvokeOnMainThread (() => {
Listviewname.scrollto(items[count-1], scrolltoposition.end, false)
});
});
https://stackoverflow.com/questions/56256802
复制相似问题