C# 将文本框绑定到浮点值。无法输入点/逗号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14600842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bind textbox to float value. Unable to input dot / comma
提问by LukeSolar
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?
例如,当我尝试在文本框中输入 DOT 或逗号时,1.02
或者83,33
文本框阻止我输入这样的值(并且输入变为红色)。文本框绑定到浮动属性。为什么?
I have bound a textbox to a float Property Power
of a class implementing INotifyPropertyChanged
.
我已将文本框绑定到Power
实现INotifyPropertyChanged
.
private float _power;
public float Power
{
get { return _power; }
set
{
_power = value;
OnPropertyChanged("Power");
}
}
In Xaml
在 Xml 中
<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.
也试过十进制,但它也不起作用。对于字符串一切正常。
采纳答案by yonigozman
Try adding a StringFormat definition to the binding. Like so:
尝试向绑定添加 StringFormat 定义。像这样:
<TextBox Name="txtPower" Height="23"
TextWrapping="Wrap" Text="{Binding Path=Power, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged,StringFormat=N2}"></TextBox>
回答by xmedeko
If you have .NET 4.5 or newer, you may enforce the pre 4.5 behaviour
如果您有 .NET 4.5 或更高版本,则可以强制执行 4.5 之前的行为
System.Windows.FrameworkCompatibilityPreferences.KeepTextBoxDisplaySynchronizedWithTextProperty = false;
See Sebastian Lux's blog:
With .NET 4.5 it is no longer possible to enter a separator character (comma or dot) with UpdateSourceTrigger = PropertyChanged
by default. Microsoft says, this intended.
请参阅Sebastian Lux 的博客:在 .NET 4.5 中UpdateSourceTrigger = PropertyChanged
,默认情况下不再可能输入分隔符(逗号或点)。微软表示,这是有意为之。
回答by Hisham
to fix dot and comma issue in textbox binding to decimal or float
修复文本框绑定到十进制或浮点数中的点和逗号问题
1- UpdateSourceTrigger = LostFocus
2- add string format StringFormat={}{0:#.##} to escape unneeded zeros
<TextBox Name="txtPower" Height="23"
TextWrapping="Wrap" Text="{Binding Path=Power, Mode=TwoWay,
UpdateSourceTrigger=LostFocus ,StringFormat={}{0:#.##}}"></TextBox>