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

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

问题描述

我想创建一个的ScrollViewer ,它包装 ContentControl中以下行为:
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.

问题是知道何时一个滚动已发生,因为用户滚动和当它发生,因为内容大小改变。我试着玩了 ScrollChangedEventArgs ScrollChangedEvent 的,但不能让它的工作。

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.

推荐答案

要结束这code会自动滚动时,内容的增加,如果它是previously滚动一路下跌。

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>

身后code:

Code behind:

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天全站免登陆