我有一个WPF应用程序(MVVM)。我想限制用户在TextBox中输入多个特定值。 假设该值为'100',那么用户应该不能输入101等。我试过下面的代码。限制TextBox输入达到特定值而不会干扰光标位置
XAML:
<TextBox Text="{Binding SearchText}" FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}" Name="SearchTextBox" TextChanged="TextBox_TextChanged"/>
CODE:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null && !string.IsNullOrEmpty(textBox.Text))
{
int searchIndex = 0;
int count = 100;
int.TryParse(textBox.Text, out searchIndex);
if (textBox != null && !string.IsNullOrEmpty(textBox.Text))
{
if (searchIndex > Count)
{
textBox.Text = textBox.Text.Substring(0, textBox.Text.Length - 1);
}
}
}
}
有了这个代码,我能够进入比特定值更限制用户。但问题是,当我设置文本框的文本,然后光标移动到第一个数字。有没有解决方案?
更好的找到wpf的NumericUpDown控件 – ASh