或者,创建一个可以在整个应用程序中重用的附加行为:)
例子:
用法:
<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;
    }
  }
}
}