0

I have a problem with the WPF textbox control. I want to enter only numeric values into it. The simple solution is to call the function isNumeric() in its PreviewKeyDown event but the problem is that if I copy a number to the clipboard and then paste it into the textbox, the check code does not get called. How can I handle pasted numbers?

dandan78
  • 13,328
  • 13
  • 64
  • 78
Shashank
  • 6,117
  • 20
  • 51
  • 72

3 Answers3

0

See DataObject.AddPastingHandler or see this question for a more generalized solution to your problem.

Community
  • 1
  • 1
Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
0

I use a own class which is is derived from TextBox. In the constructor I make a CommandBinding() with ApplicationCommands.Paste. In the "CanPaste" Method I check the pasted text (can not show example code since it is from work).

pulp

pulp
  • 698
  • 1
  • 6
  • 13
-1

if you are using cinch, just use the attached behavior from this excellent framework. but if not you can be inspired by this link, where he (the author of cinch) is solving this by an attached behavior: http://www.codeproject.com/KB/WPF/CinchII.aspx#NumericAtt

Edit: The magic lies in here, where he "disables" pasting

        TextBox tb = sender as TextBox;
        if (tb == null)
            return;

        tb.PreviewTextInput -= tbb_PreviewTextInput;
        DataObject.RemovePastingHandler(tb, OnClipboardPaste);

        bool b = ((e.NewValue != null && e.NewValue.GetType() == typeof(bool))) ?
            (bool)e.NewValue : false;
        if (b)
        {
            tb.PreviewTextInput += tbb_PreviewTextInput;
            DataObject.AddPastingHandler(tb, OnClipboardPaste);
        }
Tobias
  • 35,886
  • 1
  • 20
  • 23