Alex Rivera | Logout

How do I create an Autoscrolling TextBox

Asked 2012-04-10T22:33:17.343
28

I have a WPF application that contains a multiline TextBox that is being used to display debugging text output.

How can I set the TextBox so that as text is appended to the box, it will automatically scroll to the bottom of the textbox?

  • I'm using the MVVM pattern.
  • Ideally a pure XAML approach would be nice.
  • The TextBox itself is not necessarily in focus.
Edit
Report

1 Answer

4

Hmm this seemed like an interesting thing to implement so I took a crack at it. From some goggling it doesn't seem like there is a straight forward way to "tell" the Textbox to scroll itself to the end. So I thought of it a different way. All framework controls in WPF have a default Style/ControlTemplate, and judging by the looks of the Textbox control there must be a ScrollViewer inside which handles the scrolling. So, why not just work with a local copy of the default Textbox ControlTemplate and programmaticlly get the ScrollViewer. I can then tell the ScrollViewer to scroll its Contents to the end. Turns out this idea works.

Here is the test program I wrote, could use some refactoring but you can get the idea by looking at it:

Here is the XAML:

<Window x:Class="WpfApplication3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication3="clr-namespace:WpfApplication3"
        Title="MainWindow" Height="350" Width="525">
  <Window.Resources>
    <!--The default Style for the Framework Textbox-->
    <SolidColorBrush x:Key="DisabledForegroundBrush" Color="#888" />
    <SolidColorBrush x:Key="DisabledBackgroundBrush" Color="#EEE" />
    <SolidColorBrush x:Key="WindowBackgroundBrush" Color="#FFF" />
    <SolidColorBrush x:Key="SolidBorderBrush" Color="#888" />
    <ControlTemplate x:Key="MyTextBoxTemplate" TargetType="{x:Type TextBoxBase}">
      <Border x:Name="Border" CornerRadius="2" Padding="2" Background="{StaticResource WindowBackgroundBrush}"
              BorderBrush="{StaticResource SolidBorderBrush}" BorderThickness="1">
        <ScrollViewer Margin="0" x:Name="PART_ContentHost" />
      </Border>
      <ControlTemplate.Triggers>
        <Trigger Property="IsEnabled" Value="False">
          <Setter TargetName="Border" Property="Backgrou
answered 2012-04-11T04:39:33.037

Your Answer