2

I'm trying to make a simple calculator, and it has to focus on the last number so that when the text is too long, the user can still see what he/she is typing. Also, when the caret is not at the end of the string (arrow keys used), pressing a number button will put it back to the end of the string. How do you do this?

uhhh
  • 19
  • 4

1 Answers1

3

Set the CaretIndex to the end of input like this when text input is received.

TextBoxName.CaretIndex = TextBoxName.Text.Length - 1;

If you’re trying to create a calculator like that in Windows10, then the textbox should be read only. You can set the TextAlignment to Right to display the text from right as in Windows calculator. Since the textbox is readonly, when user clicks on some number that string needs to be concatenated to the textbox. The logic is very simple.

You can google for wpf calculator and find some good examples.

If you’re having a 2 textbox and 1 result textbox type calculator, then you can follow the method I mentioned above to achieve the expected behavior.

ViVi
  • 4,339
  • 8
  • 29
  • 52
  • This is a nice addition to KeyboardFocus from here: https://stackoverflow.com/questions/20294658/focusedelement-is-not-being-honoured/20299923#20299923 Just add the Focus invokation to a separate method and include CaretIndex change. – GeorgiG Aug 19 '19 at 06:04