Search code examples
c#wpftextboxcursor-position

WPF (with C#) TextBox Cursor Position Problem


I have a WPF C# program where I attempt to delete certain characters from a text box at TextChanged event. Say, for instance, the dollar sign. Here is the code I use.

private void txtData_TextChanged(object sender, TextChangedEventArgs e)
{
      string data = txtData.Text;

      foreach( char c in txtData.Text.ToCharArray() )
      {
            if( c.ToString() == "$" )
            {
                  data = data.Replace( c.ToString(), "" );
            }
      }

      txtData.Text = data;
}

The problem I have is that whenever the user enters $ sign (Shift + 4), at the TextChanged event it removes the $ character from the textbox text alright, but it also moves the cursor to the BEGINNING of the text box which is not my desired functionality.

As a workaround I thought of moving the cursor the the end of the text in the text box, but the problem there is that if the cursor was positioned at some middle position then it would not be very user friendly. Say, for instance the text in the textbox was 123ABC and if I had the cursor after 3, then moving the cursor to the end of the text would mean that at the next key stroke user would enter data after C, not after 3 which is the normal functionality.

Does anybody have an idea why this cursor shift happens?


Solution

  • Its not an answer to your question, but probably a solution for your problem:

    How to define TextBox input restrictions?

    If it is overkill for you, set e.Handled = true for all characters you want to avoid in PreviewKeyDown (use Keyboard.Modifiers for SHIFT key) or PreviewTextInput.

    Try TextBox.CaretIndex for restoring cursor position in TextChanged event.

    Hope it helps.