【问题标题】:WPF TextBox no Space allowed [duplicate]WPF文本框不允许空格[重复]
【发布时间】:2017-08-02 09:46:04
【问题描述】:

我希望用户只在文本框中输入数字 (0-9)。 我正在使用以下代码来防止用户写字母和除数字以外的其他字符,但我无法避免用户使用 TextBox 中的空间。

private void CheckIsNumeric(TextCompositionEventArgs e)
{
    int result;

    if (!(int.TryParse(e.Text, out result)))
    {
       e.Handled = true;
       MessageBox.Show("!!!no content!!!", "Error", 
                       MessageBoxButton.OK, MessageBoxImage.Exclamation);
    }
}

我已经尝试过使用类似的东西

if (Keyboard.IsKeyDown(Key.Space))
{ //...}

但没有成功。

感谢您的帮助。

【问题讨论】:

  • 我也试过了,它也允许空间。
  • 对重复问题地址中已接受答案的评论并支持该问题:“[Space] 不会触发 PreviewTextInput 事件”。您从哪个事件中调用您的 CheckIsNumeric 方法?
  • 哦,抱歉,我一定忽略了这一点。我正在使用 PreviewTextInput 事件,这将是问题所在。我用 textbox.Text.Replace(" ","") 绕过了我的问题。所以现在所有的空格都被删除了,这对我来说已经足够好了。
  • 如果您已将 TextBox 的 Text 属性绑定到视图模型中的某个属性,则只需让该属性的设置器执行以下操作: set { _foo = value.Replace(" ", " "); }
  • 我不知道为什么这个问题被关闭为重复。它与引用的问题有关,但非常具体,应该留下。

标签: c# wpf textbox


【解决方案1】:

为您的文本框注册 KeyPress 事件 并添加此代码。

private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
    {
        e.Handled = true;
    }

    // If you want to allow decimal numeric value in you textBox then add this too 
    if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
    {
        e.Handled = true;
    }
}

【讨论】:

  • WPF TextBox 没有 KeyPress 方法....
【解决方案2】:

在检查之前检查空格,或者只是正确的空格。因此,用户可以根据需要进行尽可能多的间隔,并且不会改变任何内容。

private void CheckIsNumeric(TextCompositionEventArgs e)
{
    int result;
  string removedSpaces =  e.Text.Replace(" ","");
    if (!(int.TryParse(removedSpaces, out result)))
    {
       e.Handled = true;
       MessageBox.Show("!!!no content!!!", "Error", 
                       MessageBoxButton.OK, MessageBoxImage.Exclamation);
    }
}

【讨论】:

  • 感谢您的回答,但这不会改变任何事情。正如我被告知 PreviewTextInput 事件不会对空间做出反应,所以我需要一种完全不同的方法。
  • 我们可以限制的唯一方法是使用 KeyDown 事件 e.Handled=e.Key==Key.Space。
猜你喜欢
  • 1970-01-01
  • 2016-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-08
  • 1970-01-01
  • 1970-01-01
  • 2021-06-27
相关资源
最近更新 更多