Gyp*_*psy 7 c# data-binding wpf
我有一个关于Float数据类型和UpdateSourceTriggerin的有趣问题WPF。我有一个带有浮点数据类型的属性并将它绑定到一个TextBox和一组UpdateSourceTriggerBinding to PropertyChanged,但WPF不让我输入 '.' 在TextBox除非我更改UpdateSourceTrigger 为LostFocus。我认为这是因为我们无法键入“。” 在浮点值的末尾。我不知道如何修复它,因为我需要输入“。” 并设置UpdateSourceTrigger为PropertyChanged。
该物业是:
public float? Amount
{
get;set;
}
Run Code Online (Sandbox Code Playgroud)
在 XAML 中:
<TextBox
Text="{Binding Amount , UpdateSourceTrigger=PropertyChanged}"/>
Run Code Online (Sandbox Code Playgroud)
如果您在绑定中添加 StringFormat 语句,也许会有所帮助:
<TextBox
Text="{Binding Amount, StringFormat='{}{##.##}', UpdateSourceTrigger=PropertyChanged}"/>
Run Code Online (Sandbox Code Playgroud)
更新:我看到我的第一个答案引发了一些绑定错误。
另一种选择是使用转换器(可以工作,但有点脏;-)):
...
<Window.Resources>
<local:FloatConverter x:Key="FloatConverter" />
</Window.Resources>
...
<TextBox Text="{Binding Amount, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource FloatConverter}}"></TextBox>
Run Code Online (Sandbox Code Playgroud)
转换器:
public class FloatConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// return an invalid value in case of the value ends with a point
return value.ToString().EndsWith(".") ? "." : value;
}
Run Code Online (Sandbox Code Playgroud)
}
| 归档时间: |
|
| 查看次数: |
3645 次 |
| 最近记录: |