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; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Views { /// /// TurinRobotWind.xaml 的交互逻辑 /// public partial class TurinRobotWind : UserControl { public TurinRobotWind() { InitializeComponent(); } #region 屏蔽非法输入 TextBox TxtBox { get; set; } Regex Rex { get; set; } /// /// 限制非法字符输入(可输入数字与小数点) /// /// /// private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { TxtBox = sender as TextBox; Rex = new Regex("[^0-9.]+"); if (TxtBox.Text.Contains(".") && e.Text == ".") { e.Handled = true; return; } e.Handled = Rex.IsMatch(e.Text); } TextChange[] change { get; set; } /// /// 屏蔽中文输入和非法字符粘贴输入 /// /// /// private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { TxtBox = sender as TextBox; change = new TextChange[e.Changes.Count]; e.Changes.CopyTo(change, 0); int offset = change[0].Offset; if (change[0].AddedLength > 0) { double num = 0; if (!Double.TryParse(TxtBox.Text, out num)) { TxtBox.Text = TxtBox.Text.Remove(offset, change[0].AddedLength); TxtBox.Select(offset, 0); } } } #endregion } }