在TextBox中突出显示文本的方法不一致 [英] Method to highlighting Text in TextBox is inconsistent
问题描述
目前我正在使用这个方法来突出显示 TextBox 中的文本,但它有时会起作用.
Currently I am using this method to highlight text inside a TextBox, but it works just sometimes.
此代码必须验证输入的文本中是否包含空格.如果文本中有空格,则应警告用户,然后必须突出显示 TextBox 内的文本:
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?
推荐答案
选择当前没有焦点的 textBox 的长度时可能会出现问题.
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;
}
也可以使用 textBox.SelectAll() 代替当前的解决方案:
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);
}
这篇关于在TextBox中突出显示文本的方法不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!