private static void OnTextBoxTextChanged(Object sender, TextChangedEventArgs args) { TextBox source = (TextBox)sender; String value = source.Text; if (String.IsNullOrWhiteSpace(value) || !NumberTextBoxHelper.IsValid(source, value)) { source.Text = NumberTextBoxHelper.GetDefault(source)?.ToString(); } }
private static void OnTextBoxPreviewTextInput(Object sender, TextCompositionEventArgs args) { String value; TextBox source = (TextBox)sender; if (source.SelectionLength == 0) { value = source.Text .Insert(source.SelectionStart, args.Text); } else { value = source.Text .Remove(source.SelectionStart, source.SelectionLength) .Insert(source.SelectionStart, args.Text); } args.Handled = !NumberTextBoxHelper.IsValid(source, value); }
private static Boolean IsValid(TextBox source, String value) { if (value == null) { return(false); } Int32?minimum = NumberTextBoxHelper.GetMinimum(source); Int32?maximum = NumberTextBoxHelper.GetMaximum(source); if (value.Length == 1 && value[0] == '-') { if (minimum.HasValue && minimum.Value >= 1) { return(false); } return(true); } if (!Int32.TryParse(value, out Int32 number)) { return(false); } if (minimum.HasValue && number < minimum.Value) { return(false); } if (maximum.HasValue && number > maximum.Value) { return(false); } return(true); }
private static void OnTextBoxPasteEventHandler(Object sender, DataObjectPastingEventArgs args) { String value; TextBox source = (TextBox)sender; if (!args.DataObject.GetDataPresent(typeof(String))) { args.CancelCommand(); return; } String clipboard = (String)args.DataObject.GetData(typeof(String)); if (String.IsNullOrWhiteSpace(clipboard)) { args.CancelCommand(); return; } if (source.SelectionLength == 0) { value = source.Text .Insert(source.SelectionStart, clipboard); } else { value = source.Text .Remove(source.SelectionStart, source.SelectionLength) .Insert(source.SelectionStart, clipboard); } if (!NumberTextBoxHelper.IsValid(source, value)) { args.CancelCommand(); return; } }