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?
Asked
Active
Viewed 3,111 times
0
-
Check this http://stackoverflow.com/questions/1268552/how-do-i-get-a-textbox-to-only-accept-numeric-input-in-wpf – anivas Jul 11 '11 at 08:22
-
http://stackoverflow.com/questions/938145/make-wpf-textbox-as-cut-copy-and-paste-restricted – Shashank Sep 05 '11 at 12:14
-
above link Show the Correct Way to Prevent Copy Paste – Shashank Sep 05 '11 at 12:14
3 Answers
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