0

I am currently trying to prevent a user from inputting anything aside from numbers into a textbox.

I currently have a Textbox with a textchange event which calls a relay command. however I am not able to effect the textbox from the relay command.

I have tried directly settings the textbox.text and that has not worked, nor has trying to return the string.

Here is my code

XAML

<TextBox x:Name="TextBox"  Margin="5,5,0,0" Grid.Column="1" Grid.Row="3"  HorizontalAlignment="Left" Width="31"  ">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="TextChanged">
                            <command:EventToCommand Command="{Binding TextBoxTextChanged,Mode=TwoWay}"
                                                    CommandParameter="{Binding Path=Text, ElementName=TextBox}" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </TextBox>

View Model

DaysBackTextChanged = new RelayCommand<string>(daysBackText =>
        {
            Func<string> function = () => 
            {
                if (!Regex.IsMatch(daysBackText, "[^0-9]+"))
                {
                    //return TextBox.Text;
                    return "X";

                }
                else
                {
                    return "Y";

                }
            };

        });
Jason D
  • 1
  • 2
  • Possible duplicate of [How do I get a TextBox to only accept numeric input in WPF?](https://stackoverflow.com/questions/1268552/how-do-i-get-a-textbox-to-only-accept-numeric-input-in-wpf) – Ron Beyer Mar 29 '18 at 02:33

1 Answers1

0

Modify your XAML to add a PreviewTextInput event in the TextBox

 PreviewTextInput="NumbersOnly"

Now,let's use Regex,shall we ?

 using System.Text.RegularExpressions;

 private void NumbersOnly(object sender,  TextCompositionEventArgs e)
{
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
}  

Here e.Handeled is to prevent anything rather than numbers being typed.

Hope this works :)

Software Dev
  • 5,368
  • 5
  • 22
  • 45