簡體   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