Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - MVVM Textbox restrict to specific characters

Tags:

c#

mvvm

wpf

I am trying to make text box accept only specific characters.

My TextBox is bound to the following:

    private string _CompanyID;
    public string CompanyID
    {
        get { return _CompanyID; }
        set
        {
            _CompanyID = UniversalHelpers.sReturnCorrectColumnName(value);
            OnPropertyChanged("CompanyID");
        }
    }

Where this is the function that is being called:

    public static string sReturnCorrectColumnName(string sInput)
    {
        if(!string.IsNullOrWhiteSpace(sInput))
            return Regex.Replace(sInput, @"[^a-zA-Z]", string.Empty).ToUpper();
        else
            return sInput;
    }

(I am allowing only a-z & A-Z, nothing else).

Finally my TextBox looks like this:

<TextBox Text="{Binding ExcelBindings.CompanyID, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />

What I don't understand is, that user can still write anything he wants, even though my Mode is set to TwoWay.

What am I doing wrong?

like image 557
Robert J. Avatar asked Sep 14 '15 19:09

Robert J.


1 Answers

You should use a custom UI element there that restricts the input on the view-side using “classic” solutions like change listeners.

For example, you can just create a simple subtype of TextBox that overrides the OnPreviewTextInput method. There, you can decide when some input should go through, or when you want to prevent it.

For example, this is a custom TextBox that takes only characters from the ASCII alphabet:

public class AlphabetTextBox : TextBox
{
    private static readonly Regex regex = new Regex("^[a-zA-Z]+$");

    protected override void OnPreviewTextInput(TextCompositionEventArgs e)
    {
        if (!regex.IsMatch(e.Text))
            e.Handled = true;
        base.OnPreviewTextInput(e);
    }
}

Of course, you could also make the regular expression a property of the text box and allow people to set it from XAML. That way, you would get a very reusable component which you can use for various applications.

like image 94
poke Avatar answered Sep 18 '22 01:09

poke