IDataErrorInfo 与 ValueConverter
我不知何故做错了,但我无法弄清楚:
我有一个像这样的模型:
public class Person : IDataErrorInfo {
public DateTime Birthdate {
get { return _birthdate; }
set {
if (!Valid(value))
AddError("Birthdate", "Birthdate not valid");
_birthdate = value;
}
}
}
像这样的 ValueConverter:
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 注册错误?
I'm somehow doing it wrong, but I can't figure it out:
I have a model like this:
public class Person : IDataErrorInfo {
public DateTime Birthdate {
get { return _birthdate; }
set {
if (!Valid(value))
AddError("Birthdate", "Birthdate not valid");
_birthdate = value;
}
}
}
A ValueConverter like this:
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;
}
}
And a View like this:
<TextBox Text="{Binding Person.Birthdate,
Mode=TwoWay,
Converter={StaticResource DateToStringConverter},
ValidatesOnDataErrors=True}" />
If someone modifies an valid date like "1.1.1950" into an invalid date like "1.1.abc", the value does not get through to the Person and doesn't invalidate it. But a red border around the birthdate-textbox is shown. How can I keep the invalid text (to be modified by the user) and register an error for IDataErrorInfo?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论