我对 C#、Xamarin Forms 和一般编码完全陌生。我尝试过以下教程和 Microsoft 文档。但是,仍然有些东西我似乎真的无法得到。在这里,我在 Xaml 中有一个条目:
<Entry Placeholder="CPR nummer"
HorizontalOptions="FillAndExpand"
HeightRequest="50"
MinimumHeightRequest="40"
PlaceholderColor="Silver"
Keyboard="Numeric"
TextColor="Gray"
x:Name="CPRnummer"
MaxLength="11"
TextChanged="CPRnummer_TextChanged"
ReturnType="Go">
</Entry>
如您所见,不是数据绑定(我似乎找不到正确的方法)。所以我将文本更改的事件放在 .cs 文件(视图)中:
private void CPRnummer_TextChanged(object sender, TextChangedEventArgs e)
{
Regex r = new Regex(@"^\d{6}-\d{4}$");
Regex r2 = new Regex(@"^\d{1,6}");
Regex r3 = new Regex(@"^\d{6}-\d{0,4}$");
CPRnummer.Text = Regex.Replace(e.NewTextValue, "[^-0-9]", "");
CPRAccept.IsEnabled = false;
CPRAccept.Opacity = 0.5;
try
{
C1 = e.OldTextValue.Length;
}
catch (NullReferenceException)
{
if (e.OldTextValue == null)
{
C1 = 0;
}
else
{
C1 = e.OldTextValue.Length;
}
}
if (!r.IsMatch(e.NewTextValue))
{
if (e.NewTextValue.Length<7&&!r2.IsMatch(e.NewTextValue))
{
CPRnummer.Text = Regex.Replace(e.NewTextValue, "[^0-9]", "");
}
else if (e.NewTextValue.Length==6&&r2.IsMatch(e.NewTextValue) && C1<e.NewTextValue.Length) {
if (CPRnummer.Text.Length == 6)
{
CPRnummer.Text = e.NewTextValue.Insert(6, "-");
}
}
else if (e.NewTextValue.Length > 6 && !r3.IsMatch(e.NewTextValue) && C1<e.NewTextValue.Length)
{
CPRnummer.Text = Regex.Replace(e.NewTextValue, "[^0-9]", "");
if (CPRnummer.Text.Length > 6)
{
CPRnummer.Text = e.NewTextValue.Insert(6, "-");
}
}
else if (!r.IsMatch(e.NewTextValue) && e.NewTextValue.Length == 11)
{
CPRnummer.Text = "";
}
else if (e.NewTextValue.Length == 10 && e.NewTextValue.All(char.IsDigit))
{
CPRnummer.Text = e.NewTextValue.Insert(6, "-");
}
}
else
{
CPRAccept.IsEnabled = true;
CPRAccept.BackgroundColor = Color.Green;
CPRAccept.Opacity = 1;
CPRAccept.Focus();
}
不要介意糟糕的编码(我完全是初学者)。该代码对我来说足够好。每次用户在输入字段中输入内容时,它都会分析输入,并删除无效字符,并在我想要的时候插入破折号。我多次利用 e.OldTextValue + NewValue 并直接使用代码禁用/启用 Accept 按钮。我确实想了解执行此操作的 MVVM 方式。据我所知,这样做的方法是 ICommand?但是我如何能够像事件监听器那样对“文本更改”做出反应?以及如何在 ViewModel 中设置这一切?如果输入字段可以“数据绑定”,我还可以使用 e.XXX 方法+尝试捕获吗?