绑定文本框浮动值。无法输入点/逗号逗号、绑定、文本框

2023-09-03 00:49:14 作者:出来混的挨打要立正

当我尝试输入一个点或一个文本框逗号,例如 1.02 83,33 文本框prevents我输入这样一个值(和输入变为红色)。该文本框绑定到一个float属性。为什么呢?

When I try to input a DOT or a COMMA in a textbox, for example 1.02 or 83,33 the textbox prevents me to input such a value (and the input turns red). The textbox is bound to a float property. Why?

我已绑定的文本框为float属性电源 A类实现 INotifyPropertyChanged的的。

I have bound a textbox to a float Property Power of a class implementing INotifyPropertyChanged.

private float _power;

public float Power
{
    get { return _power; }
    set
    {
        _power = value;
        OnPropertyChanged("Power");
    }
}

在XAML

In Xaml

<TextBox Name="txtPower" Height="23" TextWrapping="Wrap" Text="{Binding Path=Power, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>

我没有自定义的验证,在现在没事了。

I have no custom validation at all right now.

也试过小数,但它并不能工作。对于字符串一切工​​作正常。

Also tried decimal but it does not work either. For string everything works fine.

推荐答案

尝试添加的StringFormat定义绑定。 像这样:

Try adding a StringFormat definition to the binding. Like so:

<TextBox Name="txtPower" Height="23" 
    TextWrapping="Wrap" Text="{Binding Path=Power, Mode=TwoWay, 
    UpdateSourceTrigger=PropertyChanged,StringFormat=N2}"></TextBox>