using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace CyberX8_MainPages.Unity { public class TextBoxMaxValue { public static int GetMaxValue(DependencyObject obj) { return (int)obj.GetValue(MaxValueProperty); } public static void SetMaxValue(DependencyObject obj, int value) { obj.SetValue(MaxValueProperty, value); } public static readonly DependencyProperty MaxValueProperty = DependencyProperty.RegisterAttached("MaxValue", typeof(int), typeof(TextBoxMaxValue), new PropertyMetadata(OnTextBoxPropertyChanged)); private static void OnTextBoxPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { TextBox tb = d as TextBox; if (tb == null) { return; } tb.Tag = e.NewValue; tb.TextChanged += Tb_TextChanged; } private static void Tb_TextChanged(object sender, TextChangedEventArgs e) { TextBox tb = sender as TextBox; if (tb.Text == "") { return; } string str = tb.Text; str = Regex.Replace(str, @"[^\d.\d]", ""); if (Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$")) { decimal result; decimal.TryParse(str,out result); if (result > (int)tb.Tag) { tb.Text = tb.Tag.ToString(); } } } } }