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
Similar answer to the other answers, but without the statics events and control dictionary. (IMHO, static events are best avoided if possible).
public class ScrollToEndBehavior
{
public static readonly DependencyProperty OnTextChangedProperty =
DependencyProperty.RegisterAttached(
"OnTextChanged",
typeof(bool),
typeof(ScrollToEndBehavior),
new UIPropertyMetadata(false, OnTextChanged)
);
public static bool GetOnTextChanged(DependencyObject dependencyObject)
{
return (bool)dependencyObject.GetValue(OnTextChangedProperty);
}
public static void SetOnTextChanged(DependencyObject dependencyObject, bool value)
{
dependencyObject.SetValue(OnTextChangedProperty, value);
}
private static void OnTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var textBox = dependencyObject as TextBox;
var newValue = (bool)e.NewValue;
if (textBox == null || (bool)e.OldValue == newValue)
{
return;
}
TextChangedEventHandler handler = (object sender, TextChangedEventArgs args) =>
((TextBox)sender).ScrollToEnd();
if (newValue)
{
textBox.TextChanged += handler;
}
else
{
textBox.TextChanged -= handler;
}
}
}
This is just an alternative to the other posted solutions, which were among the best I found after looking for awhile (i.e. concise & mvvm).