feat: add VerificationCodeMode.

This commit is contained in:
rabbitism
2024-03-09 17:30:11 +08:00
parent 27f613f4e4
commit 5c262c5021
4 changed files with 36 additions and 3 deletions

View File

@@ -10,7 +10,7 @@
x:Class="Ursa.Demo.Pages.VerificationCodeDemo">
<StackPanel>
<u:VerificationCode Count="4" Name="v4" CompleteCommand="{Binding CompleteCommand}"/>
<ListBox ItemsSource="{Binding #v4.Digits}"></ListBox>
<u:VerificationCode Count="4" Mode="Digit"/>
<u:VerificationCode Count="6" PasswordChar="•" Complete="VerificationCode_OnComplete" />
</StackPanel>
</UserControl>

View File

@@ -1,4 +1,5 @@
using Avalonia;
using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Ursa.Controls;

View File

@@ -47,6 +47,16 @@ public class VerificationCode: TemplatedControl
set => SetValue(PasswordCharProperty, value);
}
public static readonly StyledProperty<VerificationCodeMode> ModeProperty =
AvaloniaProperty.Register<VerificationCode, VerificationCodeMode>(
nameof(Mode), defaultValue: VerificationCodeMode.Digit | VerificationCodeMode.Letter);
public VerificationCodeMode Mode
{
get => GetValue(ModeProperty);
set => SetValue(ModeProperty, value);
}
public static readonly DirectProperty<VerificationCode, IList<string>> DigitsProperty = AvaloniaProperty.RegisterDirect<VerificationCode, IList<string>>(
nameof(Digits), o => o.Digits, (o, v) => o.Digits = v);
@@ -113,9 +123,10 @@ public class VerificationCode: TemplatedControl
base.OnTextInput(e);
if (e.Text?.Length == 1 && _currentIndex < Count)
{
var presenter = _itemsControl?.ContainerFromIndex(_currentIndex) as VerificationCodeItem;
if (presenter is null) return;
char c = e.Text[0];
if (!Valid(c, this.Mode)) return;
presenter.Text = e.Text;
Digits[_currentIndex] = e.Text;
_currentIndex++;
@@ -128,6 +139,19 @@ public class VerificationCode: TemplatedControl
}
}
private bool Valid(char c, VerificationCodeMode mode)
{
bool isDigit = char.IsDigit(c);
bool isLetter = char.IsLetter(c);
return mode switch
{
VerificationCodeMode.Digit => isDigit,
VerificationCodeMode.Letter => isLetter,
VerificationCodeMode.Digit | VerificationCodeMode.Letter => isDigit || isLetter,
_ => true
};
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);

View File

@@ -0,0 +1,8 @@
namespace Ursa.Controls;
[Flags]
public enum VerificationCodeMode
{
Letter = 1,
Digit = 2,
}