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 problem with the "ScrollToEnd" method is that the TextBox has to be visible, or it won't scroll.
Therefore a better method is to set the TextBox Selection property to end of document:
static void tb_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb == null)
{
return;
}
// set selection to end of document
tb.SelectionStart = int.MaxValue;
tb.SelectionLength = 0;
}
BTW, the memory leak handling in the first example is likely unnecessary. The TextBox is the publisher and the static Attached Property event handler is the subscriber. The publisher keeps a reference to the subscriber which can keep the subscriber alive (not the other way around.) So if a TextBox goes out of scope, so will the reference to the static event handler (i.e., no memory leak.)
So hooking up the Attached Property can be handled simpler:
static void OnAutoTextScrollChanged
(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
TextBox tb = obj as TextBox;
if (tb == null)
{
return;
}
bool b = (bool)args.NewValue;
if (b)
{
tb.TextChanged += tb_TextChanged;
}
else
{
tb.TextChanged -= tb_TextChanged;
}
}