简体   繁体   中英

how to get and set current cursor position of WPF textbox

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?

You can play with caretindex property of a text box

//You can set this property on some event
NumberOfDigits.CaretIndex = textbox.Text.Length;

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();

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();
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM