<TextBox x:Name="textBox" PreviewTextInput="textBox_PreviewTextInput" TextChanged="textBox_TextChanged"/>
private void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
// 检查输入的字符是否为数字
if (!char.IsDigit(e.Text, e.Text.Length - 1))
{
e.Handled = true;
}
}
private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
// 检查文本内容是否小于 10
if (int.TryParse(textBox.Text, out int value) && value >= 10)
{
textBox.Text = "9";
textBox.CaretIndex = textBox.Text.Length;
}
}