如何在 TextBox 上设置正则表达式? [英] How can I set Regular Expression on TextBox?

查看:88
本文介绍了如何在 TextBox 上设置正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 WPF 文本框上设置正则表达式?我希望文本框接受某种预定义格式的输入.可能吗?

How can I set a regular expression on WPF TextBox? I want the textbox to accept input in some predefined format. Is it possible?

推荐答案

您有几个选择:

  • 您可以创建一个 ValidationRule 子类(见下文)并将其添加到您的 Binding 的 Validators 属性中
  • 您可以在绑定的属性上设置 ValidationCallback,如果值错误则抛出异常,并使用 此技术 用于轻松显示验证错误
  • 您可以创建一个附加属性,为 TextBox.TextChanged 属性注册一个事件处理程序,并实现您自己的验证错误通知机制
  • 您可以在后面的代码中使用带有 TextBox_Changed 处理程序的普通 TextBox
  • 您可以从附加属性中处理 PreviewKeyDown 和 PreviewTextInput,如下所示此处
  • 您可以使用屏蔽文本框 正如 Jan 所提到的
  • You can create a ValidationRule subclass (see below) and add it to your Binding's Validators property
  • You can set a ValidationCallback on your bound property, throw an exception if the value is wrong, and use this technique for easily showing validation errors
  • You can create an attached property that registers an event handler for the TextBox.TextChanged property and implement your own validation error notification mechanism
  • You can use a normal TextBox with an TextBox_Changed handler in code behind
  • You can handle PreviewKeyDown and PreviewTextInput from an attached property as shown here
  • You can use a masked text box as mentioned by Jan

对于任意正则表达式,我通常会使用 WPF 的内置验证功能或对绑定属性进行验证.对于特定需求,PreviewKeyDown/PreviewTextInput 或屏蔽文本框可能更好.

For arbitrary regexes I would generally use WPF's built-in validation features or do the validation on the bound property. For specific needs the PreviewKeyDown/PreviewTextInput or masked text box might be better.

以下是创建 ValidationRule 子类的方法:

Here is how you would create a ValidationRule subclass:

public class RegexValidationRule : ValidationRule
{
  ... // Declare Regex property and Message property

  public override ValidationResult Validate(object value, CultureInfo cultureInfo)
  {
    if(Regex.IsMatch((string)value))
      return ValidationResult.ValidResult;
    else
      return new ValidationResult(false, Message);
  }
}

这篇关于如何在 TextBox 上设置正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆