如何使用滚动条使WPF TextBox在添加行时自动滚动到底部?

Igo*_*Oks 23 .net wpf scroll

例如,像Visual Studio的"输出"窗口一样.

有没有办法在XAML中做到这一点?

Sko*_*ski 49

您可以随时向该TextBox添加内容,或者当您收听事件时,TextChanged会触发此方法: TextBoxBase.ScrollToEnd().


bit*_*onk 8

你可以写一个附加属性,甚至更好的行为是监听TextChanged事件,并滚动到下回调.


Lit*_*Bit 7

有一种方法可以在 XAML 中执行此操作,您可以使用此样式像控制台一样显示它(请注意缺点,它只是看起来像控制台,但并不完全像它一样)

        <Style x:Key="ConsoleTextBox" TargetType="{x:Type TextBox}">
            <Setter Property="IsReadOnly" Value="True"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="TextBox">
                        <ScrollViewer RenderTransformOrigin="0.5,0.5" VerticalScrollBarVisibility="Auto">
                            <ScrollViewer.RenderTransform>
                                <ScaleTransform ScaleY="-1"/>
                            </ScrollViewer.RenderTransform>
                            <TextBox Text="{TemplateBinding Text}" RenderTransformOrigin="0.5,0.5">
                                <TextBox.RenderTransform>
                                    <ScaleTransform ScaleY="-1"/>
                                </TextBox.RenderTransform>
                            </TextBox>
                        </ScrollViewer>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
Run Code Online (Sandbox Code Playgroud)

它是如何工作的

在 TextBox 内部,一个 ScrollViewer 被垂直翻转(“新”行添加在底部)

在 ScrollViewer 中,还有另一个文本框垂直翻转以正确显示文本(而不是颠倒)。

使用样式

将其包含在您的 App.xaml 中或通过 ResourceDictionary 并将 TextBox 的样式设置为 ConsoleTextBox。

<TextBox Style="{StaticResource ConsoleTextBox}"/>
Run Code Online (Sandbox Code Playgroud)

缺点

  • 当您从此“控制台”复制文本时,将没有换行符。
  • 用鼠标滚动被反转


Gui*_*ino 5

Visual Studio 输出窗口的行为是特殊的,因为它只会在插入符号位于文本框末尾时保持自动向下滚动,这允许您检查输出而不会在添加新行时受到干扰。

我对这段代码有这样的行为

bool scrollToEnd = TbEvents.CaretIndex == TbEvents.Text.Length;
TbEvents.AppendText(text + Environment.NewLine);
if (scrollToEnd)
{
    TbEvents.CaretIndex = TbEvents.Text.Length;
    TbEvents.ScrollToEnd();
}
Run Code Online (Sandbox Code Playgroud)