Reputation: 5561
I want to get the current cursor position from a WPF TextBox. If a TextBox
contains text abhishek
and cursor is blinking after abhi
then i want that index, so that later after clearing the TextBox
programmatically and assigning some other or same text programmatically I want to make the cursor blink just after 4 characters.
I have tried get cursor position like this,
_tempFuncName = txtFunctionName.Text;
_cursorPosition = txtFunctionName.SelectionStart;
_selectionLength = txtFunctionName.SelectionLength;
And set back at some later stage from other event like this,
txtFunctionName.Text = _tempFuncName;
txtFunctionName.SelectionStart = _cursorPosition;
txtFunctionName.SelectionLength = _selectionLength;
Here underscore variables are page level variables.
This code is not working. Is there some other approach?
Upvotes: 17
Views: 29324
Reputation: 51
For me, setting the focus only didn't help, but scrolling to the caret did.
txt_logArea.Select(txt_logArea.Text.Length, 0);
txt_logArea.ScrollToCaret();
Upvotes: 0
Reputation: 2154
You can play with caretindex property of a text box
//You can set this property on some event
NumberOfDigits.CaretIndex = textbox.Text.Length;
Upvotes: 17
Reputation: 5561
txtFunctionName.Text = _tempFuncName;
txtFunctionName.SelectionStart = _cursorPosition;
txtFunctionName.SelectionLength = _selectionLength ;
these statements are sufficient enough to do the req thing. i was making mistake in choosing event to write code. Thanks everyone.
Upvotes: 0
Reputation: 6543
You just need to add one line to set focus on textbox otherwise everything is working fine.
txtFunctionName.Text = _tempFuncName;
txtFunctionName.SelectionStart = _cursorPosition;
txtFunctionName.SelectionLength = _selectionLength ;
txtFunctionName.Focus();
Upvotes: 5