1

我创建了一个 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) == '-');
}

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

4

4 回答 4

1

我同意@nit,但补充说您也可以使用以下内容

textBox.PreviewTextInput = new TextCompositionEventHandler((s, e) => e.Handled = 
    !e.Text.All(c => Char.IsNumber(c) && c != ' '));
于 2013-09-11T14:11:51.797 回答
1

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

例子:

用法:

<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;
    }
  }
}
}
于 2013-09-11T14:48:24.840 回答
1

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

于 2013-09-11T14:08:20.000 回答
0

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

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

另外我建议您使用 TextChanged 事件,因为如果您在TextBox.

于 2013-09-11T14:12:59.060 回答