in WPF Textbox WPF applications often need to limit the TextBox to only receive digital input. Whether it is an integer or a decimal, this is necessary for various applications.
Use PreviewTextInput and ISTEXTALLOWED
In order to achieve this function, you can use Incident:
PreviewTextInput
In the event processing program, you can use the
<code class="language-xml"><TextBox PreviewTextInput="PreviewTextInput"></TextBox></code>
PreviewTextInput
This method uses regular expressions to verify the input to meet the needs of the application. IsTextAllowed
<code class="language-csharp">private static readonly Regex _regex = new Regex("[^0-9.-]+"); //匹配不允许的文本的正则表达式 private static bool IsTextAllowed(string text) { return !_regex.IsMatch(text); } private void PreviewTextInput(object sender, TextCompositionEventArgs e) { if (!IsTextAllowed(e.Text)) { e.Handled = true; } }</code>
In order to further limit the input, you can use the
event:
This ensures that the data that pasted to the TextBox also meet the required input conditions. Note that is corrected here DataObject.Pasting
, which is more in line with the parameter type of the
<code class="language-xml"><TextBox DataObject.Pasting="TextBoxPasting"></TextBox></code>
The above is the detailed content of How to Restrict a WPF TextBox to Accept Only Numeric Input?. For more information, please follow other related articles on the PHP Chinese website!