Numeric Data Entry in WPF

前端 未结 17 2586
情话喂你
情话喂你 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:47

    public class NumericTextBox : TextBox
    {
        public NumericTextBox()
            : base()
        {
            DataObject.AddPastingHandler(this, new DataObjectPastingEventHandler(CheckPasteFormat));
        }
    
        private Boolean CheckFormat(string text)
        {
            short val;
            return Int16.TryParse(text, out val);
        }
    
        private void CheckPasteFormat(object sender, DataObjectPastingEventArgs e)
        {
            var isText = e.SourceDataObject.GetDataPresent(System.Windows.DataFormats.Text, true);
    
            if (isText)
            {
                var text = e.SourceDataObject.GetData(DataFormats.Text) as string;
                if (CheckFormat(text))
                {
                    return;
                }
            }
    
            e.CancelCommand();
        }
    
        protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)
        {
            if (!CheckFormat(e.Text))
            {
                e.Handled = true;
            }
            else
            {
                base.OnPreviewTextInput(e);
            }
        }
    }
    

    Additionally you may customize the parsing behavior by providing appropriate dependency properties.

提交回复
热议问题