我有Xamarin TextInput。这是一种“ mm / yy”格式。我需要在第二个符号后插入/
。
我有这种方法可以在2个字符后添加/
private static string AppendAtPosition(string baseString, int position, string character)
{
var sb = new StringBuilder(baseString);
for (int i = position; i < sb.Length; i += (position + character.Length))
sb.Insert(i, character);
return sb.ToString();
}
而且我这样称呼它
ExpiresInput.EditingChanged += (object sender, EventArgs e) =>
{
var creditcardyear = ExpiresInput.Text;
if (creditcardyear.Length <= 2) return;
if (creditcardyear.Length > 2)
{
ExpiresInput.Text = AppendAtPosition(creditcardyear, 2, "/");
}
if (creditcardyear.Length == 5) {
return;
}
但是例如,当我想插入22/12
时,有这个。
我该如何解决?
ExpiresInput.EditingChanged += (object sender, EventArgs e) =>
{
var currentText = ExpiresInput.Text;
if (currentText.Length == 1)
return;
int strLength = currentText.Length;
if (Char.IsDigit(currentText, strLength -1) && Char.IsDigit(currentText, strLength - 2))
currentText = $"{currentText}/";
}
此代码在每两位数字后添加“ /”。确定没有在文本框中键入任何其他字符后,需要删除最后的“ /”。