WPF TextBox 使用 StringFormat 键入问题

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

在 WPF 中的

TextBox
中通过
StringFormat='{}{0:F2}
格式化为 2 位小数时,有没有办法“绕过”点并“覆盖”小数点?

当我在最初显示“0.00”的文本框中输入“1.23”时,它会写入“1.23.00”。我不想输入“1”,然后用右箭头移动到点后,然后输入“23”。

我应该在代码隐藏中处理输入的文本来处理点并调整输入的文本,还是有更直接的方法来实现它?

wpf textbox string-formatting
1个回答
0
投票

我认为添加的

FrameworkCompatibilityPreferences.KeepTextBoxDisplaySynchronizedWithTextProperty = false;
没有影响(我将其添加到
App
构造函数中)并且还没有研究如何处理文化。

我快速编写了这个回调,它似乎有效:

private static void tbx_PreviewKeyDown(object sender, KeyEventArgs e)
{
    var tbx = sender as TextBox;

    var text = tbx.Text;

    if (e.Key == Key.Decimal) // '.' is processed as decimal separator?
    {
        tbx.CaretIndex += 1;

        e.Handled = true;
    }

    if (e.Key == Key.Delete && text[tbx.CaretIndex] == '.')
    {
        e.Handled = true;
    }
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.