将字符串格式设置为 'D' 需要第一次按两次键才能将数据输入文本框 wpf

Setting String Format to 'D' requires two key press for the first time for the data to enter in a textbox wpf

这是我的文本框 xaml

<TextBox HorizontalAlignment="Left" TextWrapping="NoWrap" Text="{Binding Path=PointChangeRate,UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True,TargetNullValue='', StringFormat=D}" VerticalAlignment="Center" Margin="10" Grid.Column="1" Grid.Row="1" Width="160" Height="24"/>

这是我的 属性 视图模型

[Required(ErrorMessage = "PointChangeRate is Required")]
[RegularExpression("^[0-9]{1,5}([.][0-9]{1,5})?$", ErrorMessage = "PointChangeRate cannot have more than 5 decimal points")]
[CustomValidate(GroupID = "PointCalculationSettings")]
public Nullable<double> PointChangeRate
{
    get
    {
        return this._trackingConfig.PointChangeRate;
    }
    set
    {                               
        this._trackingConfig.PointChangeRate = value;
        OnPropertyChanged("PointChangeRate");
    }
}

问题是视图模型中的 属性 会在第一次按键时更新(用设置中的断点检查它)。但是,文本框仅在第二次按键时设置为值。这仅在 属性 为空时第一次发生。

当我使用退格键清除文本然后重新开始输入时,问题并没有持续存在。很奇怪!

我费心将字符串格式设置为 'D',这样我就可以允许用户输入“.”文本框中的值。

我找到了一些替代方案,如下所述。但解决方法似乎并不令人信服 TextBox Won't Allow me to enter in a decimal

如果您检查 Visual Studio 中的调试输出,您可以在尝试输入第一个数字后看到以下错误消息:

System.Windows.Data Error: 6 : 'StringFormat' converter failed to convert value '5' (type 'Double'); fallback value will be used, if available. BindingExpression:Path=PointChangeRate; DataItem='MainWindow' (Name=''); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') FormatException:'System.FormatException: Format specifier was invalid.

如果您查看 Decimal ("D") Format Specifier 的文档,它清楚地指出:

This format is supported only for integral types.

视图模型中的 属性 类型为 double? (Nullable<double>),它不是 integral type.

所以我认为 StringFormatD 的用法在这里是错误的。

在绑定上设置 Delay 并不是一个糟糕的解决方案,尽管如其他答案中所引用。这将使用户有时间在按下句点后实际输入另一个数字。

你的情况正好是this