我創建一個包含消息的ListView的聊天應用程序。當發送/接收新消息時,ListView應滾動到新消息。滾動到列表視圖中的新項目爲UWP
我使用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);
}
}
}
使用VisualTreeExtensions然而,位置調用TransformPoint總是返回{0, 0}
後,我在做什麼錯?
你得到listviewitem你想滾動? – Archana
不要將ListView包裝在ScrollViewer中,它可以自動滾動。要訪問其內部的'ScrollViewer'(例如,調用其'ChangeView'方法滾動到給定的像素偏移量),使用'ListView.GetScrollViewer()'。 – andreask
您是否檢查[this](http://stackoverflow.com/questions/16866309/listbox-scroll-into-view-with-mvvm)? – AVK