如何让 WPF TextBox 关心小数点?

问题描述 投票:0回答:2

所以我有一个只允许数字和小数点的

TextBox
。我希望用户只允许输入 1 个小数点。

这是在

PreviewTextInput
事件上触发的代码:(有些代码有点多余,但它可以完成任务)

    private void PreviewTextInput(object sender, TextCompositionEventArgs e)
    {

        TextBox textBox = (TextBox)sender;

        if (e.Text == ".")
        {

            if (textBox.Text.Contains("."))
            {

                e.Handled = true;
                return;

            }

            else
            {
                //Here I am attempting to add the decimal point myself
                textBox.Text = (textBox.Text + ".");
                e.handled = true;
                return;

            }

        }
        else
        {
            e.Handled = !IsTextAllowed(e.Text);
            return;
        }
    }

    private static bool IsTextAllowed(string text)
    {
        Regex regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
        return !regex.IsMatch(text);
    }

问题是输入的第一个小数点在后面跟一个数字之前不是“有效”。因此,如果用户输入

123.
并且您要设置
breakpoint
并检查
textBox.text
的值,则它将是
123
。我知道发生这种情况是因为
textBox
绑定到
Double
所以它试图变得“聪明”并忘记那些当前“无关紧要”的值(“.”)。

我的代码不应该有任何问题,我只是希望强制

textBox
希望跳过一些不必要的(?)自动格式化。

有没有办法让

textBox
“关心”第一个小数点?

可能重复从未得到答复。

*是否有不同的方法来限制小数位数?”(我在这方面做了很多研究,我认为没有其他选择。)

c# wpf textbox
2个回答
0
投票

如果只是限制您想要的字符,也许与字符串格式绑定之类的东西可以满足您的需求

这里是 double 格式的一个很好的例子

这将是在代码中绑定到 ViewModel 的示例

    <TextBox Text="{Binding LimitedDouble,StringFormat={}{0:00.00}}"></TextBox>

0
投票
private void txtDecimal_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!Char.IsDigit(e.KeyChar) && e.KeyChar != '\b' && e.KeyChar!='.')
    {
        e.Handled = true;
    }
    if (e.KeyChar == '.' && txtDecimal.Text.Contains("."))
    {
        e.Handled = true;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.