如何自动滚动 ScrollViewer - 仅当用户未更改滚动位置时 [英] How to automatically scroll ScrollViewer - only if the user did not change scroll position

查看:32
本文介绍了如何自动滚动 ScrollViewer - 仅当用户未更改滚动位置时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在包装 ContentControlScrollViewer 中创建以下行为:
ContentControl 高度增加时,ScrollViewer 应该自动滚动到最后.这很容易通过使用 ScrollViewer.ScrollToEnd() 实现.
但是,如果用户使用滚动条,则不应再发生自动滚动.这类似于 VS 输出窗口中发生的情况.

I would like to create the following behaviour in a ScrollViewer that wraps ContentControl:
When the ContentControl height grows , the ScrollViewer should automatically scroll to the end. This is easy to achive by using ScrollViewer.ScrollToEnd().
However, if the user uses the scroll bar, the automatic scrolling shouldn't happen anymore. This is similar to what happens in VS output window for example.

问题是要知道何时因用户滚动而发生滚动,以及何时因内容大小改变而发生滚动.我尝试使用 ScrollChangedEventScrollChangedEventArgs,但无法让它工作.

The problem is to know when a scrolling has happened because of user scrolling and when it happened because the content size changed. I tried to play with the ScrollChangedEventArgsof ScrollChangedEvent, but couldn't get it to work.

理想情况下,我不想处理所有可能的鼠标和键盘事件.

Ideally, I do not want to handle all possible Mouse and keyboard events.

推荐答案

如果之前一直向下滚动,此代码将在内容增长时自动滚动到结尾.

This code will automatically scroll to end when the content grows if it was previously scrolled all the way down.

XAML:

<Window x:Class="AutoScrollTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
    <ScrollViewer Name="_scrollViewer">
        <Border BorderBrush="Red" BorderThickness="5" Name="_contentCtrl" Height="200" VerticalAlignment="Top">
        </Border>
    </ScrollViewer>
</Window>

背后的代码:

using System;
using System.Windows;
using System.Windows.Threading;

namespace AutoScrollTest
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 2);
            timer.Tick += ((sender, e) =>
                {
                    _contentCtrl.Height += 10;

                    if (_scrollViewer.VerticalOffset == _scrollViewer.ScrollableHeight)
                    {
                        _scrollViewer.ScrollToEnd();
                    }
                });
            timer.Start();
        }
    }
}

这篇关于如何自动滚动 ScrollViewer - 仅当用户未更改滚动位置时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆