在wpf应用程序中,我使用INPC绑定: textbox to int和double属性。
应用程序逻辑必须在UpdateSourceTrigger上使用“UpdateSourceTrigger”。还实现了具有数据注释属性的INotifyDataErrorInfo接口。
当我清除textbox时,我会在调试输出窗口中看到绑定异常。
System.Windows.Data Error: 7 : ConvertBack cannot convert value '' (type 'String'). BindingExpression:Path=Power; DataItem='Auto' (HashCode=64554036); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') FormatException:'System.FormatException: Input string has invalid format.
at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)
at System.String.System.IConvertible.ToDouble(IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at MS.Internal.Data.SystemConvertConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture)
at System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)'我觉得这不太好。
我可以包装模型类(装饰器模式),并在该类中具有良好的验证逻辑。只需添加字符串属性和逻辑,以避免绑定异常。
避免这些例外情况有多重要?
在这种情况下,是否应该对模型类进行包装?这个案子的最佳做法是什么?
我用这个问题编写的示例代码。
<TextBox Text="{Binding Power, UpdateSourceTrigger=PropertyChanged}"/>public class Auto : INotifyPropertyChanged
{
string _model;
private double _power;
private int _volume;
public event PropertyChangedEventHandler PropertyChanged;
private void Set<T>(ref T field, T value, [CallerMemberName]string propertyName = "")
{
if (EqualityComparer<T>.Default.Equals(field, value)) return;
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string Model
{
get => _model;
set => Set(ref _model, value);
}
public double Power
{
get => _power;
set => Set(ref _power, value);
}
public int Volume
{
get => _volume;
set => Set(ref _volume, value);
}
}发布于 2019-10-18 11:24:05
,避免这些异常有多重要?
不重要,因为框架已经为您处理了它们。
是否应该在这种情况下包装为模型类?
不,不要使用string属性来保存int和double值。
这个案例的最佳实践是什么?
忽略绑定错误或实现您自己的转换器:
public class DoubleConverter : 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)
{
if (!double.TryParse(value.ToString(), out double d))
return Binding.DoNothing;
return d;
}
}使用:
<TextBox>
<TextBox.Text>
<Binding Path="Power" UpdateSourceTrigger="PropertyChanged">
<Binding.Converter>
<local:DoubleConverter />
</Binding.Converter>
</Binding>
</TextBox.Text>
</TextBox>https://stackoverflow.com/questions/58437347
复制相似问题