【问题标题】:Method to highlighting Text in TextBox is inconsistent在 TextBox 中突出显示文本的方法不一致
【发布时间】:2014-06-25 04:08:00
【问题描述】:

目前我正在使用 this 方法来突出显示 TextBox 中的文本,但它有时会起作用。

此代码必须验证输入的文本中是否包含空格。如果文本中有空格,则应警告用户,然后必须突出显示 TextBox 内的文本:

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;
}

为什么这种方法不能一直为我工作,我可以做些什么来解决它?

【问题讨论】:

  • 请考虑使用一个简单的按键 javascript 事件来取消用户输入的任何空格...这样会带来更好的用户体验。
  • @Eric 我觉得是注意力不集中的问题。
  • Valadate 和 DataError 是更好的用户体验。消息框很突兀。

标签: c# wpf textbox


【解决方案1】:

当您选择当前没有焦点的文本框长度时可能会出现问题。

您可以尝试添加检查焦点吗?

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() 代替当前解决方案:

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);

}

【讨论】:

  • c# 代码为if(!textBox.Focus())。我试过了,它成功了一次,我很有希望,但是在其他尝试中它失败了......
  • 你能描述在哪些情况下它会失败吗?
  • 实际上,如果元素已经有了焦点,你不应该调用 Focus 方法。所以检查 textbox.Focused - 是否有意义。
  • 没关系,它正在工作。是我的错。但为了清楚起见,当我使用 textBox.Focused 时,它表示 textBox 不包含 Focused 的定义。
  • 啊,好的。那么 textBox.SelectAll() 方法呢?它存在吗?
猜你喜欢
  • 1970-01-01
  • 2011-04-22
  • 1970-01-01
  • 1970-01-01
  • 2011-03-26
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
相关资源
最近更新 更多