如何使用文本框 UWP 输入货币

How to input currency using a text box UWP

我有一个绑定到 decimal? 的文本框,它是 class 的一部分:

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

然而,这仍然允许我输入字母字符并且不会更新 class 中的十进制值。

我应该如何处理 decimal? 到文本框的输入?

不确定这是否是您要查找的内容,但此代码仅允许 numbers/digits 并阻止粘贴到文本框中。

XAML:

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

这些方法可以这样实现:

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;
            }
        }