我尝试在 UAP 中使用新的 Behavior-Feature。我使用这种行为:
public sealed class AutoScrollToLastItemBehavior : Behavior<ListView>
{
private bool _collectionChangedSubscribed;
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SelectionChanged += SelectionChanged;
AssociatedObject.DataContextChanged += DataContextChanged;
}
private void SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ScrollToBottom();
}
private void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
ScrollToBottom();
}
private void DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
{
var collection = AssociatedObject.ItemsSource as INotifyCollectionChanged;
if (collection == null || _collectionChangedSubscribed) return;
collection.CollectionChanged += CollectionChanged;
_collectionChangedSubscribed = true;
}
private void ScrollToBottom()
{
var selectedIndex = AssociatedObject.Items?.Count - 1;
if (!selectedIndex.HasValue || selectedIndex < 0)
return;
AssociatedObject.SelectedIndex = selectedIndex.Value;
AssociatedObject.UpdateLayout();
AssociatedObject.ScrollIntoView(AssociatedObject.SelectedItem);
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.SelectionChanged -= SelectionChanged;
AssociatedObject.DataContextChanged -= DataContextChanged;
var collection = AssociatedObject.ItemsSource as INotifyCollectionChanged;
if (collection == null || !_collectionChangedSubscribed) return;
collection.CollectionChanged -= CollectionChanged;
_collectionChangedSubscribed = false;
}
}
这段代码运行良好。但我希望当用户与 ListView 交互时自动滚动停止。我找到了一些示例,但其中大多数基于 WPF,并且某些功能或属性在 UWP 中不存在。
所以实际上我没有找到一种方法来实现一个自动滚动,如果用户自己滚动它就会停止工作。有人可能对此有想法吗?
问候