using System; using System.Collections.Generic; using System.Linq; using System.Net.Mime; using System.Text; //---------------------------------------------------------------- //Module Name: $safeprojectname$ //Purpose: //CopyRight: Muchinfo //History: //---------------------------------------------------------------- //DateTime 2016/8/24 11:03:31 //Author //Description Create //---------------------------------------------------------------- using System.Windows; using System.Windows.Input; using Xceed.Wpf.Toolkit; namespace Muchinfo.WPF.Controls { public class DecimalNumBox : DecimalUpDown { private string _tempText; /// /// 小数位数 /// public int DecimalCount { get { return (int)GetValue(DecimalCountProperty); } set { SetValue(DecimalCountProperty, value); } } // Using a DependencyProperty as the backing store for DecimalCount. This enables animation, styling, binding, etc... public static readonly DependencyProperty DecimalCountProperty = DependencyProperty.Register("DecimalCount", typeof(int), typeof(DecimalNumBox), new PropertyMetadata(0)); public int MaxTextLength { get { return (int)GetValue(MaxTextLengthProperty); } set { SetValue(MaxTextLengthProperty, value); } } // Using a DependencyProperty as the backing store for MaxTextLength. This enables animation, styling, binding, etc... public static readonly DependencyProperty MaxTextLengthProperty = DependencyProperty.Register("MaxTextLength", typeof(int), typeof(DecimalNumBox), new PropertyMetadata(20)); protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e) { _tempText = Text; if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || (e.Key >= Key.D0 && e.Key <= Key.D9)) { if (!string.IsNullOrWhiteSpace(Text) && Text.Contains('.') && DecimalCount>0) { string[] strArr = TextBox.Text.Split('.'); if (strArr.Length >0&&TextBox.CaretIndex <= strArr[0].Length) { e.Handled = false; } else if (strArr.Length >= 1 && TextBox.CaretIndex > strArr[0].Length&&strArr[1].Length < DecimalCount) { e.Handled = false; } else { e.Handled = true; } } else { e.Handled = false; } } else if (((e.Key == Key.OemPeriod) || e.Key == Key.Decimal) && DecimalCount>0&& !string.IsNullOrWhiteSpace(Text) && !Text.Contains('.')) { e.Handled = false; } else if (e.Key == Key.Tab) { e.Handled = false; } else { e.Handled = true; } if (!string.IsNullOrWhiteSpace(Text)&&MaxTextLength <= Text.Length) { e.Handled = true; } } protected override void OnKeyUp(KeyEventArgs e) { var index = TextBox.CaretIndex; //base.OnKeyUp(e); if (string.IsNullOrWhiteSpace(Text)) { this.Value = 0; return; } if (DecimalCount > 0) { var pattern = "^[0-9]+(.[0-9]{0," + DecimalCount + "})?$"; if (!System.Text.RegularExpressions.Regex.IsMatch(Text, pattern)) { Text = _tempText; this.Value= this.ConvertTextToValue(Text); TextBox.CaretIndex = index; } } } } }