Articles in categories

Articles

An AttachedProperty to make a WPF (multiline) TextBox automatically scroll to the end. (autoscrolling)

An AttachedProperty to make a WPF (multiline) TextBox automatically scroll to the end -> autoscrolling-textbox

Found this solution on StackOverflow.

using System;
using System.Windows;
using System.Windows.Controls;

namespace Stieven.Utils
{
  /// <summary>
  /// Attached Property to make a (multiline) TextBox always scroll to the end
  /// http://stackoverflow.com/questions/10097417/how-do-i-create-an-autoscrolling-textbox
  /// </summary>
  public static class TextBoxUtilities
  {

    public static readonly DependencyProperty AlwaysScrollToEndProperty = 
      DependencyProperty.RegisterAttached("AlwaysScrollToEnd",typeof(bool),typeof(TextBoxUtilities),new PropertyMetadata(false, AlwaysScrollToEndChanged));

    private static void AlwaysScrollToEndChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
      var tb = sender as TextBox;
      if (tb != null)
      {
        bool alwaysScrollToEnd = (e.NewValue != null) && (bool)e.NewValue;
        if (alwaysScrollToEnd)
        {
          tb.ScrollToEnd();
          tb.TextChanged += TextChanged;
        }
        else
        {
          tb.TextChanged -= TextChanged;
        }
      }
      else
      {
        throw new InvalidOperationException("The attached AlwaysScrollToEnd property can only be applied to TextBox instances.");
      }
    }

    public static bool GetAlwaysScrollToEnd(TextBox textBox)
    {
      if (textBox == null)
      {
        throw new ArgumentNullException("textBox");
      }

      return (bool)textBox.GetValue(AlwaysScrollToEndProperty);
    }

    public static void SetAlwaysScrollToEnd(TextBox textBox, bool alwaysScrollToEnd)
    {
      if (textBox == null)
      {
        throw new ArgumentNullException("textBox");
      }

      textBox.SetValue(AlwaysScrollToEndProperty, alwaysScrollToEnd);
    }

    private static void TextChanged(object sender, TextChangedEventArgs e)
    {
      ((TextBox)sender).ScrollToEnd();
    }
  }
}

Usage:

<TextBox Grid.Row="1"
	        Name="textBoxLog"
	        Margin="5"
		TextWrapping="Wrap"
		AcceptsReturn="True"
		VerticalScrollBarVisibility="Auto"
		Utils:TextBoxUtilities.AlwaysScrollToEnd="True"
		Text="{Binding LogText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

Also available as a download: