How to find that ScrollViewer is scrolled to the end in WPF?

可紊 提交于 2020-01-19 00:43:28

问题


I have a ScrollViewer instance in my custom control... I need the requirement that whether scorollview is scrolled to the End? Is there any way?


回答1:


You can check this with this way:

...
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"); 
}



回答2:


Here is my MVVM-friendly version:

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;
    }

}


来源:https://stackoverflow.com/questions/10793717/how-to-find-that-scrollviewer-is-scrolled-to-the-end-in-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!