TextBoxMaxValue.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. namespace CyberX8_MainPages.Unity
  10. {
  11. public class TextBoxMaxValue
  12. {
  13. public static int GetMaxValue(DependencyObject obj)
  14. {
  15. return (int)obj.GetValue(MaxValueProperty);
  16. }
  17. public static void SetMaxValue(DependencyObject obj, int value)
  18. {
  19. obj.SetValue(MaxValueProperty, value);
  20. }
  21. public static readonly DependencyProperty MaxValueProperty =
  22. DependencyProperty.RegisterAttached("MaxValue", typeof(int), typeof(TextBoxMaxValue), new PropertyMetadata(OnTextBoxPropertyChanged));
  23. private static void OnTextBoxPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  24. {
  25. TextBox tb = d as TextBox;
  26. if (tb == null)
  27. {
  28. return;
  29. }
  30. tb.Tag = e.NewValue;
  31. tb.TextChanged += Tb_TextChanged;
  32. }
  33. private static void Tb_TextChanged(object sender, TextChangedEventArgs e)
  34. {
  35. TextBox tb = sender as TextBox;
  36. if (tb.Text == "")
  37. {
  38. return;
  39. }
  40. string str = tb.Text;
  41. str = Regex.Replace(str, @"[^\d.\d]", "");
  42. if (Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$"))
  43. {
  44. decimal result;
  45. decimal.TryParse(str,out result);
  46. if (result > (int)tb.Tag)
  47. {
  48. tb.Text = tb.Tag.ToString();
  49. }
  50. }
  51. }
  52. }
  53. }