C# 带值转换器的IDataErrorInfo
我有点做错了,但我想不出来: 我有一个这样的模型:C# 带值转换器的IDataErrorInfo,c#,wpf,idataerrorinfo,valueconverter,C#,Wpf,Idataerrorinfo,Valueconverter,我有点做错了,但我想不出来: 我有一个这样的模型: public class Person : IDataErrorInfo { public DateTime Birthdate { get { return _birthdate; } set { if (!Valid(value)) AddError("Birthdate", "Birthdate not valid"); _birthdate = value; }
public class Person : IDataErrorInfo {
public DateTime Birthdate {
get { return _birthdate; }
set {
if (!Valid(value))
AddError("Birthdate", "Birthdate not valid");
_birthdate = value;
}
}
}
public class DateToStringConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
return date.Date.ToShortDateString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
DateTime result;
if (DateTime.TryParse(text, out result))
{
return result;
}
return DependencyProperty.UnsetValue;
}
}
<TextBox Text="{Binding Person.Birthdate,
Mode=TwoWay,
Converter={StaticResource DateToStringConverter},
ValidatesOnDataErrors=True}" />
像这样的值转换器:
public class Person : IDataErrorInfo {
public DateTime Birthdate {
get { return _birthdate; }
set {
if (!Valid(value))
AddError("Birthdate", "Birthdate not valid");
_birthdate = value;
}
}
}
public class DateToStringConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
return date.Date.ToShortDateString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
DateTime result;
if (DateTime.TryParse(text, out result))
{
return result;
}
return DependencyProperty.UnsetValue;
}
}
<TextBox Text="{Binding Person.Birthdate,
Mode=TwoWay,
Converter={StaticResource DateToStringConverter},
ValidatesOnDataErrors=True}" />
还有这样一种观点:
public class Person : IDataErrorInfo {
public DateTime Birthdate {
get { return _birthdate; }
set {
if (!Valid(value))
AddError("Birthdate", "Birthdate not valid");
_birthdate = value;
}
}
}
public class DateToStringConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
return date.Date.ToShortDateString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
DateTime result;
if (DateTime.TryParse(text, out result))
{
return result;
}
return DependencyProperty.UnsetValue;
}
}
<TextBox Text="{Binding Person.Birthdate,
Mode=TwoWay,
Converter={StaticResource DateToStringConverter},
ValidatesOnDataErrors=True}" />
如果有人将有效日期(如“1.1.1950”)修改为无效日期(如“1.1.abc”),则该值不会传递给此人,也不会使其无效。但生日文本框周围会显示一个红色边框。如何保留无效文本(由用户修改)并为IDataErrorInfo注册错误?setter中是否应该有else语句?如果(!Valid(value)…else _birth=value;否,为什么?从外部调用集合,我认为它应该真正设置值(或抛出ArgumentException)。如果值无效,则对象处于无效状态。忽略设置将使对象处于有效状态-但使用旧值。我认为这是错误的。