【问题标题】:WPF TextBox doesn't allow symbolsWPF TextBox 不允许符号
【发布时间】:2013-09-15 14:27:03
【问题描述】:

我创建了一个 wpf 文本框,并为该文本框生成了一个 KeyDown 事件,以仅允许字母数字、空格、退格、'-' 来实现我使用以下代码

private void txtCompanyName_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
   e.Handled = !(char.IsLetterOrDigit((char)KeyInterop.VirtualKeyFromKey(e.Key)) || (char)KeyInterop.VirtualKeyFromKey(e.Key) == (char)Keys.Back || (char)KeyInterop.VirtualKeyFromKey(e.Key) == (char)Keys.Space || (char)KeyInterop.VirtualKeyFromKey(e.Key) == '-');
}

但它也允许在文本框中使用符号。我该如何解决这个问题。抱歉我的英语不好。提前致谢

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    使用PreviewKeyDown 事件而不是KeyDown 事件。如果处理,它将不允许触发 keydown 事件。为了实现完整的功能,您还应该为textBox.PreviewTextInput 设置相同的逻辑

    【讨论】:

      【解决方案2】:

      我同意@nit,但补充一点,您也可以使用以下

      textBox.PreviewTextInput = new TextCompositionEventHandler((s, e) => e.Handled = 
          !e.Text.All(c => Char.IsNumber(c) && c != ' '));
      

      【讨论】:

        【解决方案3】:

        另外,创建一个可以在整个应用程序中重用的附加行为:)

        例子:

        用法:

        <TextBox x:Name="textBox" VerticalContentAlignment="Center" FontSize="{TemplateBinding FontSize}" attachedBehaviors:TextBoxBehaviors.AlphaNumericOnly="True" Text="{Binding someProp}">
        

        代码:

        public static class TextBoxBehaviors
        {
        
        public static readonly DependencyProperty AlphaNumericOnlyProperty = DependencyProperty.RegisterAttached(
          "AlphaNumericOnly", typeof(bool), typeof(TextBoxBehaviors), new UIPropertyMetadata(false, OnAlphaNumericOnlyChanged));
        
        static void OnAlphaNumericOnlyChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
        {
          var tBox = (TextBox)depObj;
        
          if ((bool)e.NewValue)
          {
            tBox.PreviewTextInput += tBox_PreviewTextInput;
          }
          else
          {
            tBox.PreviewTextInput -= tBox_PreviewTextInput;
          }
        }
        
        static void tBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
          // Filter out non-alphanumeric text input
          foreach (char c in e.Text)
          {
            if (AlphaNumericPattern.IsMatch(c.ToString(CultureInfo.InvariantCulture)))
            {
              e.Handled = true;
              break;
            }
          }
        }
        }
        

        【讨论】:

          【解决方案4】:

          您可以检查是否启用了大写锁定或按下了某个 shift 键(例如 Keyboard.IsKeyDown(Key.LeftShift);),如果是这种情况,您只需留出空格并返回:

          if (condition)
              e.Handled = e.Key == Key.Back || e.Key == Key.Space;
          

          我还建议您使用 TextChanged 事件,因为如果您在 TextBox 中粘贴一些内容,它也会被触发。

          【讨论】:

            猜你喜欢
            • 2015-02-04
            • 1970-01-01
            • 2012-05-30
            • 2019-04-16
            • 1970-01-01
            • 1970-01-01
            • 2014-02-12
            • 2014-11-02
            • 2011-09-20
            相关资源
            最近更新 更多