Numeric Data Entry in WPF

前端 未结 17 2564
情话喂你
情话喂你 2020-12-02 05:38

How are you handling the entry of numeric values in WPF applications?

Without a NumericUpDown control, I\'ve been using a TextBox and handling its PreviewKeyDown eve

17条回答
  •  借酒劲吻你
    2020-12-02 05:58

    Combining the ideas from a few of these answers, I have created a NumericTextBox that

    • Handles decimals
    • Does some basic validation to ensure any entered '-' or '.' is valid
    • Handles pasted values

    Please feel free to update if you can think of any other logic that should be included.

    public class NumericTextBox : TextBox
    {
        public NumericTextBox()
        {
            DataObject.AddPastingHandler(this, OnPaste);
        }
    
        private void OnPaste(object sender, DataObjectPastingEventArgs dataObjectPastingEventArgs)
        {
            var isText = dataObjectPastingEventArgs.SourceDataObject.GetDataPresent(System.Windows.DataFormats.Text, true);
    
            if (isText)
            {
                var text = dataObjectPastingEventArgs.SourceDataObject.GetData(DataFormats.Text) as string;
                if (IsTextValid(text))
                {
                    return;
                }
            }
    
            dataObjectPastingEventArgs.CancelCommand();
        }
    
        private bool IsTextValid(string enteredText)
        {
            if (!enteredText.All(c => Char.IsNumber(c) || c == '.' || c == '-'))
            {
                return false;
            }
    
            //We only validation against unselected text since the selected text will be replaced by the entered text
            var unselectedText = this.Text.Remove(SelectionStart, SelectionLength);
    
            if (enteredText == "." && unselectedText.Contains("."))
            {
                return false;
            }
    
            if (enteredText == "-" && unselectedText.Length > 0)
            {
                return false;
            }
    
            return true;
        }
    
        protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)
        {
            e.Handled = !IsTextValid(e.Text);
            base.OnPreviewTextInput(e);
        }
    }
    

提交回复
热议问题