Wpf NumericTextBox

This simple code provides a complete NumericTextBox. Whe arey blocking paste operations and the space character.

public class NumericTextBox : TextBox
    {
        public NumericTextBox()
        {
            PreviewTextInput += NumericTextBox_PreviewTextInput;
            PreviewKeyDown += NumericTextBox_PreviewKeyDown;
            DataObject.AddPastingHandler(this, OnPaste);
        }

        void NumericTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Space) { e.Handled = true; }
        }

        void NumericTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            int outValue;
            e.Handled = !int.TryParse(e.Text, out outValue);
        }

        private void OnPaste(object sender, DataObjectPastingEventArgs e)
        {
            var pastedText = e.DataObject.GetData(DataFormats.Text) as string;
            int outValue;
            var cancel = !int.TryParse(pastedText, out outValue);
            if (cancel) e.CancelCommand();
        }
    }
Tagged with: ,
Posted in WPF
%d bloggers like this: