How can I make a RichTextBox scroll to the end when I add a new line?

邮差的信 提交于 2019-12-12 07:25:11

问题


I have several read only RichTextBox's that are used for logging output. Since they're read only they don't seem to automatically scroll when the text is updated. I can use the TextChanged event to force a scroll to end, but is there not simply a way to set a property or something in the XAML so that scrolling happens like normal?


回答1:


I had googled for your problem and found this post. In the section "Programming the RichTextBox" author had described about getting the behavior what you had been expecting.

Please check and let me know if it is of any use.


I tried to reproduce your problem and came up with the following solution

    <Window x:Class="CheckRichTextBox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="170" Width="300">
    <StackPanel>
        <RichTextBox Height="100" Name="richTextBox1" IsReadOnly="True" VerticalScrollBarVisibility="Visible"/>
        <Button Name="btnAdd" Content="Click me to add text" VerticalAlignment="Bottom" Click="BtnAddClick" />
    </StackPanel>
</Window>

The code behind for the same is as below:

using System.Windows;

namespace CheckRichTextBox
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void BtnAddClick(object sender, RoutedEventArgs e)
        {
            richTextBox1.AppendText("You had Clicked the button for adding text\n");
            richTextBox1.ScrollToEnd();
        }
    }
}

This solves the problem of autoscroll, please check it and let me know if it is of any help.




回答2:


I solved this problem using an Interactivity trigger and a very simple action.

The action looks like this:

public class ScrollToBottomAction : TriggerAction<RichTextBox>
{
    protected override void Invoke(object parameter)
    {
        AssociatedObject.ScrollToEnd();
    }
}

Then in my XAML I have this:

<RichTextBox IsReadOnly="True" VerticalScrollBarVisibility="Auto">
     <i:Interaction.Triggers>
            <i:EventTrigger EventName="TextChanged">
                <interactivity:ScrollToBottomAction/>
            </i:EventTrigger>
     </i:Interaction.Triggers>
</RichTextBox>



回答3:


RichTextBox.AppendText("String")
RichTextBox.ScrollToCaret()

When I was adding to RichTextBox.text, ScrollToCaret() does not work.

RichTextBox.text = RichTextBox.text + "String"
RichTextBox.ScrollToCaret()


来源:https://stackoverflow.com/questions/10308475/how-can-i-make-a-richtextbox-scroll-to-the-end-when-i-add-a-new-line

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