繁体   English   中英

WPF自定义文本框,可使用Regex控制用户输入

[英]WPF Custom textbox to control user input using Regex

我的目标是编写/扩展WPF文本框,该文本框可以通过输入一些无效字符来限制用户。 因此,允许的字符将成为正则表达式。

这是我所做的:

 public class MyTextBox : TextBox
{
    static MyTextBox()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyTextBox),
         new FrameworkPropertyMetadata(typeof(MyTextBox)));
        TextProperty.OverrideMetadata(typeof(MyTextBox), new FrameworkPropertyMetadata(new PropertyChangedCallback(TextPropertyChanged)));

    }

    public MyTextBox()
    {
       PreviewTextInput +=MyTextBox_PreviewTextInput;
    }
    void MyTextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
    {
        var tb = sender as MyTextBox;
        if (tb == null) return;

        if (IsMasking(tb) && !Regex.IsMatch(e.Text, Mask))
        {
            e.Handled = true;
        }
    }

   private static bool IsMasking(MyTextBox tb)
    {
        if (string.IsNullOrWhiteSpace(tb.Mask)) return false;
        try
        {
            new Regex(tb.Mask);
        }
        catch (Exception)
        {
                           return false;
        }
        return true;
    }

    #region Mask Dependancy property
    public string Mask
    {
        get { return (string)GetValue(MaskProperty); }
        set { SetValue(MaskProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Mask.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MaskProperty =
        DependencyProperty.Register("Mask", typeof(string), typeof(MyTextBox), new PropertyMetadata(string.Empty));

    #endregion


}

用法:

 <ctrlLib:MyTextBox  Watermark="Test WM" Width="350" Margin="20" 
                        Mask="^[A-Z][0-9]{2}$"
                        PreviewTextInput="UIElement_OnPreviewTextInput"/>

所以我只允许后面跟两个整数的alpha。 我的控件甚至不接受任何字符作为输入

我在做什么错或如何解决? 我猜因为正则表达式用于输入单个字符的整个字符串并不能解决问题?

这应该可以解决问题

^[A-Za-z]*\d\d$

您已经接近了,只需要在[AZ]之后重新开始

我使它不区分大小写,并使用\\ d作为[0-9]的简写

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM