Browse Source

MaxLength Property for TextBox

pull/2864/head
Ben Carman 7 years ago
parent
commit
0486de87a6
No known key found for this signature in database GPG Key ID: 8A27B50F704C53C8
  1. 11
      src/Avalonia.Controls/TextBox.cs
  2. 18
      tests/Avalonia.Controls.UnitTests/TextBoxTests.cs

11
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
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(),

Loading…
Cancel
Save