Method to highlighting Text in TextBox is inconsistent

﹥>﹥吖頭↗ 提交于 2020-01-17 04:24:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!