How do I get a TextBox to only accept numeric input in WPF?

后端 未结 30 2732
悲哀的现实
悲哀的现实 2020-11-22 03:40

I\'m looking to accept digits and the decimal point, but no sign.

I\'ve looked at samples using the NumericUpDown control for Windows Forms, and this sample of a Num

30条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 04:20

    How about this? Works well for me. Hope I didn't miss any edge cases...

    MyTextBox.PreviewTextInput += (sender, args) =>
    {
        if (!int.TryParse(args.Text, out _))
        {
            args.Handled = true;
        }
    };
    
    DataObject.AddPastingHandler(MyTextBox, (sender, args) =>
    {
        var isUnicodeText = args.SourceDataObject.GetDataPresent(DataFormats.UnicodeText, true);
        if (!isUnicodeText)
        {
            args.CancelCommand();
        }
    
        var data = args.SourceDataObject.GetData(DataFormats.UnicodeText) as string;
        if (!int.TryParse(data, out _))
        {
            args.CancelCommand();
        }
    });
    

提交回复
热议问题