TextBoxIntegerMaskBehavior.cs 646 B

123456789101112131415161718192021222324252627
  1. using System.Windows.Controls;
  2. using System.Windows.Input;
  3. using Microsoft.Xaml.Behaviors;
  4. namespace InABox.WPF;
  5. public class TextBoxIntegerMaskBehavior : Behavior<TextBox>
  6. {
  7. protected override void OnAttached()
  8. {
  9. AssociatedObject.PreviewTextInput += PreviewTextInput;
  10. base.OnAttached();
  11. }
  12. protected override void OnDetaching()
  13. {
  14. AssociatedObject.PreviewTextInput -= PreviewTextInput;
  15. base.OnDetaching();
  16. }
  17. private void PreviewTextInput(object sender, TextCompositionEventArgs e)
  18. {
  19. if (!int.TryParse(e.Text, out int _))
  20. e.Handled = true;
  21. }
  22. }