How to get and set the current cursor position of a WPF text field

I want to get the current cursor position from a WPF text box. If a TextBox contains the text abhishek and the cursor blinks after abhi , then I want this index, so later after clearing the TextBox programmatically and assigning some other or the same text programmatically, I want the cursor to flash only after 4 characters.

I tried to get a cursor position like this,

 _tempFuncName = txtFunctionName.Text; _cursorPosition = txtFunctionName.SelectionStart; _selectionLength = txtFunctionName.SelectionLength; 

And back to some later stage from another event like this,

 txtFunctionName.Text = _tempFuncName; txtFunctionName.SelectionStart = _cursorPosition; txtFunctionName.SelectionLength = _selectionLength; 

Here, underscore variables are page level variables.

This code does not work. Is there any other approach?

+13
c # wpf
Oct 13 2018-11-11T00:
source share
4 answers

You can play with the caretindex property of the text box

 //You can set this property on some event NumberOfDigits.CaretIndex = textbox.Text.Length; 
+11
Oct 13 '11 at 7:30
source share

You just need to add one line to set focus on the text field, otherwise everything will work fine.

 txtFunctionName.Text = _tempFuncName; txtFunctionName.SelectionStart = _cursorPosition; txtFunctionName.SelectionLength = _selectionLength ; txtFunctionName.Focus(); 
+5
Oct. 13 '11 at 7:14
source share
 txtFunctionName.Text = _tempFuncName; txtFunctionName.SelectionStart = _cursorPosition; txtFunctionName.SelectionLength = _selectionLength ; 

these statements are sufficient to satisfy the req requirement. I was mistaken when choosing an event for writing code. Thanks to everyone.

0
Oct 13 '11 at 8:10
source share

For me, this helped not only set the focus, but also scroll the carriage.

''

  txt_logArea.Select(txt_logArea.Text.Length, 0); txt_logArea.ScrollToCaret(); 

''

0
Apr 12 '19 at 11:28
source share



All Articles