30

我的自定义控件中有一个ScrollViewer实例......我需要scorollview是否滚动到End的要求?有什么办法吗?

4

2 回答 2

55

您可以通过以下方式进行检查:

...
scrollViewer.ScrollChanged += OnScrollChanged;
...

private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
{
   var scrollViewer = (ScrollViewer)sender;
   if (scrollViewer.VerticalOffset == scrollViewer.ScrollableHeight)
          MessageBox.Show("This is the end"); 
}
于 2012-05-29T09:59:12.107 回答
8

这是我的 MVVM 友好版本:

public static class ScrollHelper
{
    public static readonly DependencyProperty ScrollToBottomProperty = DependencyProperty.RegisterAttached("ScrollToBottom", typeof(ICommand), typeof(ScrollHelper), new FrameworkPropertyMetadata(null, OnScrollToBottomPropertyChanged));

    public static ICommand GetScrollToBottom(DependencyObject ob)
    {
        return (ICommand) ob.GetValue(ScrollToBottomProperty);
    }

    public static void SetScrollToBottom(DependencyObject ob, ICommand value)
    {
        ob.SetValue(ScrollToBottomProperty, value);
    }

    private static void OnScrollToBottomPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        var scrollViewer = obj as ScrollViewer;

        scrollViewer.Loaded += OnScrollViewerLoaded;

    }

    private static void OnScrollViewerLoaded(object sender, RoutedEventArgs e)
    {
        (sender as ScrollViewer).Loaded -= OnScrollViewerLoaded;

        (sender as ScrollViewer).Unloaded += OnScrollViewerUnloaded;
        (sender as ScrollViewer).ScrollChanged += OnScrollViewerScrollChanged;
    }

    private static void OnScrollViewerScrollChanged(object sender, ScrollChangedEventArgs e)
    {           
        var scrollViewer = (ScrollViewer)sender;
        if (scrollViewer.VerticalOffset >= scrollViewer.ScrollableHeight)
        {
            var command = GetScrollToBottom(sender as ScrollViewer);
            if (command == null || !command.CanExecute(null))
                return;

            command.Execute(null);
        }
    }

    private static void OnScrollViewerUnloaded(object sender, RoutedEventArgs e)
    {
        (sender as ScrollViewer).Unloaded -= OnScrollViewerUnloaded;
        (sender as ScrollViewer).ScrollChanged -= OnScrollViewerScrollChanged;
    }

}
于 2015-04-07T20:19:14.403 回答