0

I have a textbox that is bounded to a decimal? that is part of a class:

<TextBox PlaceholderText="Fee" Text="{x:Bind ClassObject.Fee, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

However this still allows me to input alphabetic characters and doesn't update the decimal value in the class.

How should I handle the input of a decimal? into a textbox?

DavidSNB
  • 171
  • 1
  • 10

1 Answers1

1

Not sure if this is what you are looking for but this code only allows numbers/digits and prevents pasting into the textbox.

XAML:

<TextBox PreviewTextInput="OnlyAllowNumbers" CommandManager.PreviewExecuted="PreventPasteIntoTextbox"
</TextBox>

These methods could be implemented like this:

Class:

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

        private void PreventPasteIntoTextbox(object sender, ExecutedRoutedEventArgs e)
        {
            if (e.Command == ApplicationCommands.Copy ||
                e.Command == ApplicationCommands.Cut ||
                e.Command == ApplicationCommands.Paste)
            {
                e.Handled = true;
            }
        }
timunix
  • 609
  • 6
  • 19