验证小数
#region 验证小数 /// <summary> /// 验证小数 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void txtRoomArea_KeyDown_ForFloat(object sender, KeyEventArgs e) { TextBox txt = sender as TextBox; //屏蔽非法按键,只能输入小数 if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Subtract || e.Key == Key.Decimal) { if (txt.Text.Contains(".") && e.Key == Key.Decimal) { e.Handled = true; return; } e.Handled = false; } else if (((e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod || e.Key == Key.Subtract) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift) { if (txt.Text.Contains(".") && e.Key == Key.OemPeriod) { e.Handled = true; return; } e.Handled = false; } else { e.Handled = true; } } #endregion
TextBox内容改变的时候检测
#region TextBox_TextChanged private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { //屏蔽中文输入和粘贴输入 TextBox textBox = sender as TextBox; TextChange[] 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(textBox.Text, out num) && !textBox.Text.Equals("-")) { textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength); textBox.Select(offset, 0); } } // NoteFieldConfigModel noteField = NoteFieldConfigs.First(t => t.FfieldName == textBox.Name); // string value = string.IsNullOrEmpty(textBox.Text) == true ? null : textBox.Text; // if(string.IsNullOrEmpty(value)) // { // return; // } //if (noteField.FfieldType == 3) //{ // textBox.Text = string.Format("{0:N2}", Convert.ToDouble(value.TrimStart(','))); //} //if (noteField.FfieldType == 2 && (noteField.FimptClassID == null || noteField.FimptClassID == 0)) //{ // textBox.Text = string.Format("{0:N0}", Convert.ToDouble(value.TrimStart(','))); //} } #endregion