我想知道 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 会有这样的行为?