0

I'm fairly new to C# and WPF, but I'm trying to create a textbox that only allows up to 14 numbers and 3 periods, and another textbox that only allows 5 numbers. How can I do that? I've researched on stackoverflow with no luck for some reason. I've tried many "solutions", but those never worked for me.

Ali Shah Ahmed
  • 3,263
  • 3
  • 24
  • 22
Raymonf
  • 114
  • 1
  • 16
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Mar 04 '13 at 23:16
  • Whoops, sorry about that! – Raymonf Mar 04 '13 at 23:17
  • 2
    You are probably looking for a masked text box. See if this helps: https://wpftoolkit.codeplex.com/wikipage?title=MaskedTextBox – JDB Mar 04 '13 at 23:17
  • http://stackoverflow.com/questions/14813960/how-to-accept-only-integers-in-a-wpf-textbox/14814012#14814012 might help. – GrandMasterFlush Mar 04 '13 at 23:19
  • The problem is that I'm using MahApps.Metro and using a control for the textbox. I don't know if that will work. – Raymonf Mar 04 '13 at 23:19
  • @GrandMasterFlush I'm looking for a normal TextBox addition. Is there a way to make that work using maybe Regex or something? – Raymonf Mar 04 '13 at 23:20
  • In the link of @GrandMasterFlush there is an answer below his that gives you an easy way to test if it's a number, you can extend this example to do whatever you want to. – Rafael Mar 04 '13 at 23:28
  • I tried this once by catching the javascript keydown event on the text field. After the keydow event I checked the key that was pressed, and when a non numeric character was chosen, I cancelled typing by calling event.preventdefault(). This way I succeeded in preventing letters to be typed, but the charaters above the numbers ($%&*) couldn't be prevented so easily. Also my script prevented typing with the numpad. At that point I decided it wasn't that important for my project. – Michiel Mar 04 '13 at 23:37

2 Answers2

2

I'm looking at nakiya's solution and I can see that you don't understand what to do. I'll make full example so you can learn something from it. Take a look:

MainWindow.xaml

<TextBox TextChanged="TextBoxBase_OnTextChanged" />

MainWindow.cs

private void TextBoxBase_OnTextChanged(object sender, TextChangedEventArgs e) {
    var textBox = sender as TextBox;
    if (textBox != null) {
        string newValue = textBox.Text;
        int changed = ValidateText(ref newValue);

        int selectionStart = textBox.SelectionStart;
        textBox.Text = newValue;
        textBox.SelectionStart = selectionStart - changed;
    }
}

private int ValidateText(ref string input) {
    // If no value, return empty string
    if (input == null) return 0;

    int changed = 0;
    // Go through input string and create new string that only contains digits and period
    StringBuilder builder = new StringBuilder();
    for (int index = 0; index < input.Length; index++) {
        if (Char.IsDigit(input[index]) || input[index] == '.')
            builder.Append(input[index]);
        else changed++;
    }
    input = builder.ToString();
    return changed;
}
Aleksandar Toplek
  • 2,792
  • 29
  • 44
0

If you are willing, you can set the binding like this:

<TextBox Text="{Binding Field, UpdateSourceTrigger=PropertyChanged}" />

And then in the setter of the Field property enforce your requirement:

public string Field
{
    get { return _field; }
    set
    {
        var val = MakeNumeric(value)
        _field = value;
        OnPropertyChanged("Field");
    }
}
nakiya
  • 14,063
  • 21
  • 79
  • 118
  • "MakeNumeric", "_field" don't exist. Cannot convert from string to System.Windows.DependencyPropertyChangedEventArgs. The best overloaded method match for 'System.Windows.DependencyObject.OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs)' has some invalid arguments. – Raymonf Mar 04 '13 at 23:36
  • That's what I don't understand. I'm new to C# so I'm not too sure how things work here. :/ – Raymonf Mar 04 '13 at 23:42
  • @RBLXDev: You'd have to implement `MakeNumeric` method according to your needs. You'd also want to implement `INotifyPropertyChanged` in the class which owns `Field`. – nakiya Mar 04 '13 at 23:45
  • But how? I don't understand how to implement MakeNumeric. – Raymonf Mar 04 '13 at 23:56
  • Quoted from sneakthief "You have to create a method private string MakeNumeric(string valueToCheck) and then put whatever validation you need inside that method." – JuStDaN Mar 05 '13 at 05:56