我想知道DataGrid绑定对于不同类型的错误的行为有何不同。 我已经建立了一个示例项目:
数据类:
public class MajorEvent : INotifyPropertyChanged, IDataErrorInfo
{
private DateTime when;
public DateTime When
{
get { return when; }
set
{
if (value > DateTime.Now)
{
throw new ArgumentOutOfRangeException("value", "A Major event can't happen in the future!");
}
when = value;
}
}
public string What { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
public string this[string columnName]
{
get
{
if (columnName.Equals("What"))
{
if (string.IsNullOrEmpty(What))
{
return "An event needs an agenda!";
}
}
return string.Empty;
}
}
public string Error
{
get { return null; }
}
}
主窗口代码背后:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
dg.ItemsSource = new ObservableCollection<MajorEvent>
{
new MajorEvent {What = "Millenium celebrations", When = new DateTime(1999, 12, 31)},
new MajorEvent {What = "I Have A Dream Speach", When = new DateTime(1963, 8, 28)},
new MajorEvent {What = "First iPhone Release", When = new DateTime(2007, 6, 29)},
new MajorEvent {What = "My Birthday", When = new DateTime(1983, 5, 13)},
new MajorEvent {What = "Friends Backstabbing Day", When = new DateTime(2009, 6, 8)},
};
}
}
和MainWindow Xaml:
<Window x:Class="DataGridValidationIssue.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid x:Name="dg" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="What" Binding="{Binding What, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" Width="*"/>
<DataGridTextColumn Header="When" Binding="{Binding When, StringFormat='d', ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" Width="Auto"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
现在,关于日期列 - 当我输入未来日期(从而导致ArgumentOutOfRangeException)时,仍然可以编辑文本列。当我提供无效日期时(例如,5月35日),则无法编辑文本列。
为什么WPF的行为如此?
答案 0 :(得分:2)
DateTime
范围内的默认验证行为是当您输入无法转换为DateTime
的字符串(即5月35日或其他奇特的东西)时抛出异常。抛出异常后,TextBox
被阻止
在您的情况下,您没有检查IDataErrorInfo
实施中的日期值! (more information about IDataErrorInfo here if needed)
在默认的DateTime
验证过程之后抛出异常似乎是合乎逻辑的,因为您正在验证异常。您应该在this[string propertName]
处理日期范围中添加一个案例(我认为您必须在此处添加“When”属性的案例,测试日期范围)