how to get and set current cursor position of WPF textbox

.net, c#, wpf

Solution

You can play with caretindex property of a text box

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

Problem

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?

Original source