NumberInput.xaml.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using PixiEditor.Models.Controllers.Shortcuts;
  2. using System;
  3. using System.Text.RegularExpressions;
  4. using System.Windows;
  5. using System.Windows.Controls;
  6. using System.Windows.Input;
  7. namespace PixiEditor.Views
  8. {
  9. /// <summary>
  10. /// Interaction logic for NumerInput.xaml.
  11. /// </summary>
  12. public partial class NumberInput : UserControl
  13. {
  14. // Using a DependencyProperty as the backing store for Value. This enables animation, styling, binding, etc...
  15. public static readonly DependencyProperty ValueProperty =
  16. DependencyProperty.Register(
  17. "Value",
  18. typeof(float),
  19. typeof(NumberInput),
  20. new PropertyMetadata(0f, OnValueChanged));
  21. // Using a DependencyProperty as the backing store for Min. This enables animation, styling, binding, etc...
  22. public static readonly DependencyProperty MinProperty =
  23. DependencyProperty.Register(
  24. "Min",
  25. typeof(float),
  26. typeof(NumberInput),
  27. new PropertyMetadata(float.NegativeInfinity));
  28. // Using a DependencyProperty as the backing store for Max. This enables animation, styling, binding, etc...
  29. public static readonly DependencyProperty MaxProperty =
  30. DependencyProperty.Register(
  31. "Max",
  32. typeof(float),
  33. typeof(NumberInput),
  34. new PropertyMetadata(float.PositiveInfinity));
  35. public NumberInput()
  36. {
  37. InitializeComponent();
  38. }
  39. public float Value
  40. {
  41. get => (float)GetValue(ValueProperty);
  42. set => SetValue(ValueProperty, value);
  43. }
  44. public float Min
  45. {
  46. get => (float)GetValue(MinProperty);
  47. set => SetValue(MinProperty, value);
  48. }
  49. public float Max
  50. {
  51. get => (float)GetValue(MaxProperty);
  52. set => SetValue(MaxProperty, value);
  53. }
  54. private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  55. {
  56. NumberInput input = (NumberInput) d;
  57. input.Value = Math.Clamp((float) e.NewValue, input.Min, input.Max);
  58. }
  59. private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
  60. {
  61. Regex regex = new Regex("^[.][0-9]+$|^[0-9]*[.]{0,1}[0-9]*$");
  62. e.Handled = !regex.IsMatch((sender as TextBox).Text.Insert((sender as TextBox).SelectionStart, e.Text));
  63. }
  64. }
  65. }