我有一個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