如何使Validation.GetHasError()返回DataGrid的正确值?

时间:2016-05-22 21:45:25

标签: c# wpf validation datagrid

我有一个带输入验证的DataGrid,如果它包含验证错误,我想禁用一个按钮。我使用以下代码检查此类错误:

${CATALINA_BASE}/work

问题是编辑后, private void sequenceGrid_LostFocus(object sender, RoutedEventArgs e) { // This method is called on any click outside the current cell ((DataGrid)sender).UnselectAllCells(); if (HasError(((DataGrid)sender))) { ((dynamic)DataContext).DatagridsValidated = false; } else { ((dynamic)DataContext).DatagridsValidated = true; } } private bool HasError(DataGrid dg) { /*bool errors = (from c in (from object i in dg.ItemsSource select dg.ItemContainerGenerator.ContainerFromItem(i)) where c != null select Validation.GetHasError(c)).FirstOrDefault(x => x); return errors; */ for (int i = 0; i < dg.Items.Count; i++) { DataGridRow row = GetRow(dg, i); if (row != null && Validation.GetHasError(row)) { return true; } } return false; } public static DataGridRow GetRow(DataGrid grid, int index) { DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index); if (row == null) { // May be virtualized, bring into view and try again. grid.UpdateLayout(); grid.ScrollIntoView(grid.Items[index]); row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index); } return row; } private void sequenceGrid1_MouseLeave(object sender, MouseEventArgs e) { PreviewMouseLeftButtonDown += mouseClick; } private void mouseClick(object sender, MouseEventArgs e) { HitTestResult hitTestResult; hitTestResult = VisualTreeHelper.HitTest(sequenceGrid1, e.GetPosition(sequenceGrid1)); if (hitTestResult == null) // Click outside the datagrid { sequenceGrid1.CommitEdit(DataGridEditingUnit.Row, true); try { sequenceGrid1.Items.Refresh(); } catch { } // Edit mode still open if there is invalid input } PreviewMouseLeftButtonDown -= mouseClick; } 会返回错误的值。例如,我需要在DataGrid中单击两次以获取此方法以返回正确的值。我提到注释的代码会给出相同的结果。

如何使Validation.GetHasError()返回DataGrid的正确值?

0 个答案:

没有答案