Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WPF文本框没有';不允许使用符号_C#_Wpf - Fatal编程技术网

C# WPF文本框没有';不允许使用符号

C# WPF文本框没有';不允许使用符号,c#,wpf,C#,Wpf,我已经创建了一个wpf文本框,并为该文本框生成了一个KeyDown事件,只允许字母数字、空格、退格“-”,以实现我使用了以下代码 private void txtCompanyName_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { e.Handled = !(char.IsLetterOrDigit((char)KeyInterop.VirtualKeyFromKey(e.Key)) || (char)KeyIn

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

但它也允许在文本框中使用符号。我怎样才能解决这个问题。对不起,我的英语不好。提前感谢

使用
PreviewKeyDown
事件而不是
KeyDown
事件。如果已处理,则不允许触发keydown事件。为了实现完整的功能,您还应该为
文本框添加相同的逻辑。PreviewTestInput也
我同意@nit,但补充一点,您也可以使用以下内容:


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

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

另外,我建议您使用TextChanged事件,因为如果您将某些内容粘贴到
文本框
中,它也会被触发。或者,创建一个可在整个应用程序中重用的附加行为:)

例如:

用法:

<TextBox x:Name="textBox" VerticalContentAlignment="Center" FontSize="{TemplateBinding FontSize}" attachedBehaviors:TextBoxBehaviors.AlphaNumericOnly="True" Text="{Binding someProp}">
<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;
    }
  }
}
}