我正在使用包含消息的 ListView 创建一个聊天应用程序。当发送/接收新消息时,ListView 应该滚动到新消息。
我正在使用 MVVM,所以 ListView 看起来像
<ScrollViewer>
<ItemsControl Source="{Binding Messages}" />
</ScrollViewer>
我该怎么做?
编辑:我试图在周年更新创建行为之前的版本中进行这项工作。这是我到目前为止所拥有的:
public class FocusLastBehavior : Behavior<ItemsControl>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Items.VectorChanged += ItemsOnVectorChanged;
}
private void ItemsOnVectorChanged(IObservableVector<object> sender, IVectorChangedEventArgs @event)
{
var scroll = VisualTreeExtensions.FindVisualAscendant<ScrollViewer>(AssociatedObject);
if (scroll == null)
{
return;
}
var last = AssociatedObject.Items.LastOrDefault();
if (last == null)
{
return;
}
var container = AssociatedObject.ContainerFromItem(last);
ScrollToElement(scroll, (UIElement)container);
}
private static void ScrollToElement(ScrollViewer scrollViewer, UIElement element,
bool isVerticalScrolling = true, bool smoothScrolling = true, float? zoomFactor = null)
{
var transform = element.TransformToVisual((UIElement)scrollViewer.Content);
var position = transform.TransformPoint(new Point(0, 0));
if (isVerticalScrolling)
{
scrollViewer.ChangeView(null, position.Y, zoomFactor, !smoothScrolling);
}
else
{
scrollViewer.ChangeView(position.X, null, zoomFactor, !smoothScrolling);
}
}
}
该代码使用UWP 社区工具包中的 VisualTreeExtensions
但是,调用 TransformPoint 后的位置总是返回{0, 0}
我究竟做错了什么?