我有一个包含这个的窗口
TextBox
:
<TextBox x:Name="phoneTextBox" Margin="0,0,0,10" TextChanged="PhoneTextBox_TextChanged" />
如您所见,我正在调用一个方法名称
PhoneTextBox_TextChanged
,其代码如下:
private void PhoneTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = sender as TextBox;
var text = textBox.Text.Replace("(", "").Replace(")", "").Replace(" ", "").Replace("-", "");
if (text.Length > 11)
text = text.Substring(0, 11);
if (text.Length >= 6)
textBox.Text = $"({text.Substring(0, 2)}) {text.Substring(2, 5)}-{text.Substring(7)}";
else if (text.Length >= 2)
textBox.Text = $"({text.Substring(0, 2)}) {text.Substring(2)}";
else if (text.Length >= 1)
textBox.Text = $"({text}";
textBox.CaretIndex = textBox.Text.Length; // Mover o cursor para o final
}
最初,代码可以正确格式化直至第五个数字...从第六个数字开始,应用程序崩溃并显示以下消息:
System.ArgumentOutOfRangeException:'索引和长度必须引用一个 字符串内的位置。 Arg_ParamName_Name'
错误消息指向执行逻辑的第二个条件:
textBox.Text = $"({text.Substring(0, 2)}) {text.Substring(2, 5)}-{text.Substring(7)}";
如何解决这个问题?我期待的结果是:(99) 99999-9999。
找到解决方案:
private void PhoneTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = sender as TextBox;
var text = textBox.Text.Replace("(", "").Replace(")", "").Replace(" ", "").Replace("-", "");
// Limit the text length to a maximum of 11 characters
if (text.Length > 11)
text = text.Substring(0, 11);
// Format the text based on its length
if (text.Length >= 6)
{
// Ensure that we have enough characters for the substrings
string areaCode = text.Length >= 2 ? text.Substring(0, 2) : text;
string firstPart = text.Length >= 7 ? text.Substring(2, 5) : text.Substring(2);
string secondPart = text.Length >= 8 ? text.Substring(7) : "";
textBox.Text = $"({areaCode}) {firstPart}-{secondPart}";
}
else if (text.Length >= 2)
{
textBox.Text = $"({text.Substring(0, 2)}) {text.Substring(2)}";
}
else if (text.Length >= 1)
{
textBox.Text = $"({text}";
}
// Move the cursor to the end
textBox.CaretIndex = textBox.Text.Length;
}
说明:您遇到的错误 System.ArgumentOutOfRangeException 是因为您尝试访问超出文本字符串长度的子字符串而发生。