Browse Source

MaxLength Property for TextBox

Ben Carman 6 years ago
parent
commit
0486de87a6
2 changed files with 28 additions and 1 deletions
  1. 10 1
      src/Avalonia.Controls/TextBox.cs
  2. 18 0
      tests/Avalonia.Controls.UnitTests/TextBoxTests.cs

+ 10 - 1
src/Avalonia.Controls/TextBox.cs

@@ -59,6 +59,9 @@ namespace Avalonia.Controls
                 o => o.SelectionEnd,
                 (o, v) => o.SelectionEnd = v);
 
+        public static readonly StyledProperty<int> MaxLengthProperty =
+            AvaloniaProperty.Register<TextBox, int>(nameof(MaxLength), defaultValue: 0);
+
         public static readonly DirectProperty<TextBox, string> TextProperty =
             TextBlock.TextProperty.AddOwner<TextBox>(
                 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;

+ 18 - 0
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(),