所以,我有一个包含文本框和标签的简单视图。
<TextBox x:Name="MyIntTextBox" Text="{Binding MyInt, UpdateSourceTrigger=LostFocus, Mode=TwoWay, StringFormat={}{D2}}"/>
<Label Content="{Binding MyStr2}"/>
在 中ViewModel
,我有:
private decimal myInt;
public decimal MyInt
{
get { return myInt; }
set
{
if (value == myInt) { return; }
myInt = value;
OnPropertyChange();
OnPropertyChange("MyStr2");
}
}
public string MyStr2
{
get
{
return myInt.ToString("N2", CultureInfo.CreateSpecificCulture("en-IN"));
}
}
简单地说,TextBox
Text
绑定到一个decimal
值,并且Label
应该textbox
以正确的格式显示该值。
因为我有LostFocus
我的UpdateSourceTrigger
中TextBox
,我按下TAB
为了使validation
和binding
工作。
所以当我输入一个decimal
值时,一切正常。在Label
正确显示格式的数字。
当我输入一些垃圾非十进制值时,TextBox
Border
变为红色表示验证错误。
但是,当我在此之后输入一些有效值时,就像这样……
...然后专注于TextBox
, 砰!在TextBox
一片空白。
该Label
然而,指示正确的值。我在 中设置了断点ViewModel
,我可以看到MyInt
确实具有正确的值,在本例中为 600,但TextBox
不显示它。
我的Output
窗口中也出现以下错误:
System.Windows.Data Error: 6 : 'StringFormat' converter failed to convert value '600' (type 'Decimal'); fallback value will be used, if available. BindingExpression:Path=MyInt; DataItem='ViewModel' (HashCode=37975124); target element is 'TextBox' (Name='MyIntTextBox'); target property is 'Text' (type 'String') FormatException:'System.FormatException: Input string was not in a correct format.
at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.Format(IFormatProvider provider, String format, Object[] args)
at System.Windows.Data.BindingExpression.ConvertHelper(IValueConverter converter, Object value, Type targetType, Object parameter, CultureInfo culture)'
是否有任何简单的解决方法?还是我做错了什么?
但是,当我在此之后输入一些有效值时,就像这样……
如果您在键入它会再次努力decimal
值入TextBox
。
但解决办法,否则将执行该处理之间的转换自己的自定义转换器类decimal
和string
。
试试这个:
namespace WpfApp2
{
class DecimalToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return null;
return System.Convert.ToDecimal(value).ToString(parameter as string);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
decimal d;
if (decimal.TryParse(value.ToString(), out d))
return d;
return value;
}
}
}
<StackPanel xmlns:local="clr-namespace:WpfApp2">
<StackPanel.Resources>
<local:DecimalToStringConverter x:Key="conv" />
</StackPanel.Resources>
<TextBox x:Name="MyIntTextBox" Text="{Binding MyInt, Converter={StaticResource conv}, ConverterParameter=0.00}"/>
<Label Content="{Binding MyStr2}"/>
</StackPanel>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句