Here is a common suffix for an arbitrary number of TextBoxes.
Initializing the TextBox'es list:
private readonly List<TextBox> _textBoxes; public MainWindow() { InitializeComponent(); _textBoxes = new List<TextBox> { _textBox1, _textBox2, _textBox3 }; }
Version with KeyUp event:
private void TextBox_KeyUp(object sender, KeyEventArgs e) { if (e.Key == Key.Tab) return; var current = (TextBox)sender; if (current.Text.Any()) return; var index = _textBoxes.IndexOf(current); if (index == 0) return; var previous = _textBoxes[index - 1]; previous.Focus(); previous.CaretIndex = previous.Text.Length; }
The above version does not allow you to go through TextBoxes in the click and hold scripts. To get around this, use the TextChanged event:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { var current = (TextBox)sender; if (current.Text.Any()) return; var index = _textBoxes.IndexOf(current); if (index == 0) return; var previous = _textBoxes[index - 1]; previous.Focus(); previous.CaretIndex = previous.Text.Length; }
The third solution is with PreviewKeyDown, which only supports Key.Delete:
private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key != Key.Delete) return; var current = (TextBox)sender; if (current.Text.Length != 0) return; var index = _textBoxes.IndexOf(current); if (index == 0) return; var previous = _textBoxes[index - 1]; previous.Focus(); previous.CaretIndex = 0; }
The fourth solution is also with PreviewKeyDown, which supports both Key.Delete and Key.Back:
private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key != Key.Delete && e.Key != Key.Back) return; var current = (TextBox)sender; if (current.Text.Length != 0) return; var index = _textBoxes.IndexOf(current); if (index == 0) return; var previous = _textBoxes[index - 1]; previous.Focus(); if (e.Key == Key.Delete) previous.CaretIndex = 0; }