How to restrict numeric value paste in WPF textbox
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?
See DataObject.AddPastingHandler
or see this question for a more generalized solution to your problem.
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
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);
}
精彩评论