问题
Currently I am using this method to highlight text inside a TextBox, but it works just sometimes.
This code has to verify if there is contained a space in the entered text. If there is a space in the text the user should be warned, and then the text inside the TextBox has to be highlighted:
if (textBox.Text.Contains(" "))
{
MessageBox.Show("Sorry, the value entered must not contain any spaces.", "Please enter a valid value", MessageBoxButton.OK, MessageBoxImage.Error);
//Highlights incorrect text
textBox.SelectionStart = 0;
textBox.SelectionLength = textBox.Text.Length;
}
Why isn't this method working for me all the time and what can I do to fix it?
回答1:
It might be a problem when you are selecting length of textBox which has no focus in current moment.
Can you try to add check for focus?
if (textBox.Text.Contains(" "))
{
MessageBox.Show("Sorry, the value entered must not contain any spaces.", "Please enter a valid value", MessageBoxButton.OK, MessageBoxImage.Error);
if(!textBox.Focused)
{
textBox.Focus();
}
//Highlights incorrect text
textBox.SelectionStart = 0;
textBox.SelectionLength = textBox.Text.Length;
}
Also instead of current solution you can use textBox.SelectAll():
if (textBox.Text.Contains(" "))
{
textBox.SelectAll();
MessageBox.Show("Sorry, the value entered must not contain any spaces.", "Please enter a valid value", MessageBoxButton.OK, MessageBoxImage.Error);
}
来源:https://stackoverflow.com/questions/24394304/method-to-highlighting-text-in-textbox-is-inconsistent