diff --git a/src/Avalonia.Controls/TextBox.cs b/src/Avalonia.Controls/TextBox.cs index 6e26d1b1ff..fdc9d153e2 100644 --- a/src/Avalonia.Controls/TextBox.cs +++ b/src/Avalonia.Controls/TextBox.cs @@ -59,6 +59,9 @@ namespace Avalonia.Controls o => o.SelectionEnd, (o, v) => o.SelectionEnd = v); + public static readonly StyledProperty MaxLengthProperty = + AvaloniaProperty.Register(nameof(MaxLength), defaultValue: 0); + public static readonly DirectProperty TextProperty = TextBlock.TextProperty.AddOwner( o => o.Text, @@ -232,6 +235,12 @@ namespace Avalonia.Controls } } + public int MaxLength + { + get { return GetValue(MaxLengthProperty); } + set { SetValue(MaxLengthProperty, value); } + } + [Content] public string Text { @@ -345,7 +354,7 @@ namespace Avalonia.Controls input = RemoveInvalidCharacters(input); string text = Text ?? string.Empty; int caretIndex = CaretIndex; - if (!string.IsNullOrEmpty(input)) + if (!string.IsNullOrEmpty(input) && (MaxLength == 0 || input.Length + text.Length - (Math.Abs(SelectionStart - SelectionEnd)) <= MaxLength)) { DeleteSelection(); caretIndex = CaretIndex; diff --git a/tests/Avalonia.Controls.UnitTests/TextBoxTests.cs b/tests/Avalonia.Controls.UnitTests/TextBoxTests.cs index febc1de5f9..225eca17b2 100644 --- a/tests/Avalonia.Controls.UnitTests/TextBoxTests.cs +++ b/tests/Avalonia.Controls.UnitTests/TextBoxTests.cs @@ -460,6 +460,24 @@ namespace Avalonia.Controls.UnitTests } } + [Fact] + public void Text_Box_MaxLength_Work_Properly() + { + using (UnitTestApplication.Start(Services)) + { + var target = new TextBox + { + Template = CreateTemplate(), + Text = "abc", + MaxLength = 3, + }; + + RaiseKeyEvent(target, Key.D, KeyModifiers.None); + + Assert.Equal("abc", target.Text); + } + } + private static TestServices FocusServices => TestServices.MockThreadingInterface.With( focusManager: new FocusManager(), keyboardDevice: () => new KeyboardDevice(),