diff --git a/src/Avalonia.Controls/TextBox.cs b/src/Avalonia.Controls/TextBox.cs index 54d3af9b59..44d1a1c489 100644 --- a/src/Avalonia.Controls/TextBox.cs +++ b/src/Avalonia.Controls/TextBox.cs @@ -514,21 +514,36 @@ namespace Avalonia.Controls private void HandleTextInput(string input) { - if (!IsReadOnly) + if (IsReadOnly) { - input = RemoveInvalidCharacters(input); - string text = Text ?? string.Empty; - int caretIndex = CaretIndex; - if (!string.IsNullOrEmpty(input) && (MaxLength == 0 || input.Length + text.Length - (Math.Abs(SelectionStart - SelectionEnd)) <= MaxLength)) - { - DeleteSelection(); - caretIndex = CaretIndex; - text = Text ?? string.Empty; - SetTextInternal(text.Substring(0, caretIndex) + input + text.Substring(caretIndex)); - CaretIndex += input.Length; - ClearSelection(); - _undoRedoHelper.DiscardRedo(); - } + return; + } + + input = RemoveInvalidCharacters(input); + + if (string.IsNullOrEmpty(input)) + { + return; + } + + string text = Text ?? string.Empty; + int caretIndex = CaretIndex; + int estimatedLength = input.Length + text.Length - Math.Abs(SelectionStart - SelectionEnd); + + if (MaxLength > 0 && estimatedLength > MaxLength) + { + input = input.Remove(Math.Max(0, input.Length - (estimatedLength - MaxLength))); + } + + if (!string.IsNullOrEmpty(input)) + { + DeleteSelection(); + caretIndex = CaretIndex; + text = Text ?? string.Empty; + SetTextInternal(text.Substring(0, caretIndex) + input + text.Substring(caretIndex)); + CaretIndex += input.Length; + ClearSelection(); + _undoRedoHelper.DiscardRedo(); } }