将WPF文本框限制为数字值和小数点
>需要一个仅接受数字和小数点的WPF文本框,而不允许任何迹象? 虽然ANumericUpDown
控制似乎是一种解决方案,但它可能不符合您的应用程序的设计。 一种更灵活的方法使用PreviewTextInput
>和DataObject.Pasting
事件。
>将事件添加到您的文本框定义:PreviewTextInput
<TextBox PreviewTextInput="PreviewTextInput"></TextBox>
为了防止粘贴无效的数据,请处理PreviewTextInput
>事件:
<code class="language-csharp">private static readonly Regex _regex = new Regex("[^0-9.-]+"); // Regex for disallowed characters private static bool IsTextAllowed(string text) { return !_regex.IsMatch(text); } private void PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = !IsTextAllowed(e.Text); }</code>这些方法可确保您的文本框仅接受数字输入,从而为您的应用程序的设计量身定制了干净有效的解决方案。
以上是如何将WPF文本框中的输入限制为仅数字值和小数点?的详细内容。更多信息请关注PHP中文网其他相关文章!