Flack
Flack

Reputation: 5899

Scrolling to the end of a single line WPF TextBox

This seems like such a simple thing but I just can't get it to work.

I have a single line text box that has a lot of text. What I want to happen is that whenever the text box receives focus, it scrolls to the end of the text so that it comes into view and the cursor is at the end ready to accept new text.

In the text box's GotFocus event I call textBox.ScrollToEnd(). It looks like all this does is move the cursor to the end of the text box but not actually bring the end into view.

What am I missing?

Upvotes: 7

Views: 13028

Answers (4)

tataelm
tataelm

Reputation: 939

In my case, my textbox was inside a scrollviewer and I had to call ScrollToEnd() for scrollviewer instead textbox.

XAML

<ScrollViewer x:Name="scrollviewer">
        <TextBox TextBoxBase.TextChanged="TextChanged"/>
</ScrollViewer>

CODE

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

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292685

You should be able to do it using these members:


EDIT: not sure why ScrollToEnd isn't working... Anyway, this code works:

textBox.CaretIndex = textBox.Text.Length;
var rect = textBox.GetRectFromCharacterIndex(textBox.CaretIndex);
textBox.ScrollToHorizontalOffset(rect.Right);

Upvotes: 23

Eugeny
Eugeny

Reputation: 51

It is true - setting the caret property from code doesn't affect the view; and the caret can go outside the visible part.

kb_target_box.Focus(); // just for sure
Rect rect = kb_target_box.GetRectFromCharacterIndex(kb_target_box.CaretIndex);
kb_target_box.ScrollToHorizontalOffset(Math.Max((kb_target_box.HorizontalOffset + rect.Left - (kb_target_box.ActualWidth - 40)), 0.0));

h-scroll will follow the caret after it comes closer than 40 to the right TextBox border.

Upvotes: 5

user892381
user892381

Reputation:

This worked for me.

textBox.CaretIndex = txt.Text.Length;  
textBox.ScrollToEnd();

Upvotes: 3

Related Questions