最初的问题是 2011 年的,Datagrids 验证系统仍然存在问题,无法使用。我花了 2 天时间试图找到一个解决方案来完成以下工作:
- 我的模型项实现了 INotifyDataErrorInfo 和 INotifyPropertyChanged
- 它们位于绑定到 DataGrid 的 BindingList 中
- DataGrid 应该显示来自用户输入的验证错误以及来自不同来源的模型更改
- RowValidation-Error-mark 应该显示任何单元格是否存在验证错误,否则隐藏,无论用户当前是在编辑、提交还是对行不执行任何操作
- 无效单元格应显示带有错误文本的工具提示
- 没有错误或故障
实现此行为的唯一方法是放弃 RowValidation 和 CellValidation,而使用 RowHeader 和样式。我从网络上的各种来源复制了以下代码。我还不能对此进行广泛的测试,但乍一看它看起来很有希望。
在 DataGrids XAML 中:
<DataGrid ... local:DataGridProps.ShowCellErrorBorder="False">
<DataGrid.Resources>
<local:DataGridValidationConverter x:Key="DataGridValidationConverter" />
<Style TargetType="TextBlock" x:Key="errTemplate">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding Path=(Validation.Errors)[0].ErrorContent}
RelativeSource={x:Static RelativeSource.Self}, "/>
<Setter Property="Background" Value="LightSalmon"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
<DataGrid.RowValidationErrorTemplate>
<ControlTemplate>
</ControlTemplate>
</DataGrid.RowValidationErrorTemplate>
<DataGrid.RowHeaderTemplate>
<DataTemplate>
<Grid Margin="0,-2,0,-2"
Visibility="{Binding Path=DataContext.HasErrors,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type DataGridRow}},
Converter={StaticResource DataGridValidationConverter},
FallbackValue=Hidden}">
<Ellipse StrokeThickness="0" Fill="Red"
Width="{Binding Path=FontSize,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type DataGridRow}}}"
Height="{Binding Path=FontSize,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type DataGridRow}}}" />
<TextBlock Text="!" FontWeight="Bold" Foreground="White" HorizontalAlignment="Center"
FontSize="{Binding Path=FontSize,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type DataGridRow}}}" />
</Grid>
</DataTemplate>
</DataGrid.RowHeaderTemplate>
<DataGrid.Columns>
<DataGridTextColumn Header="Vorname" ElementStyle="{StaticResource errTemplate}"
Binding="{Binding Path=Vorname,
ValidatesOnNotifyDataErrors=True,
NotifyOnValidationError=True}" />
...
</DataGrid.Columns>
</DataGrid>
DataGridValidationConverter:
public class DataGridValidationConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((bool)value)
return Visibility.Visible;
else
return Visibility.Hidden;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
DataGridProps:
public class DataGridProps
{
public static readonly DependencyProperty ShowCellErrorBorderProperty = DependencyProperty.RegisterAttached(
"ShowCellErrorBorder", typeof(bool), typeof(DataGridProps), new PropertyMetadata(true, ShowCellErrorBorderPropertyChangedCallback));
public static bool GetShowCellErrorBorder(DependencyObject element)
{
return (bool)element.GetValue(ShowCellErrorBorderProperty);
}
public static void SetShowCellErrorBorder(DependencyObject element, bool value)
{
element.SetValue(ShowCellErrorBorderProperty, value);
}
private static void ShowCellErrorBorderPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
if (GetShowCellErrorBorder(dependencyObject)) return;
var dg = dependencyObject as DataGrid;
if (null != dg)
{
dg.Loaded += (sender, args) =>
{
var scrollView = dg.Template.FindName("DG_ScrollViewer", dg) as ScrollViewer;
if (null == scrollView) return;
var scrollContent = scrollView.Template.FindName("PART_ScrollContentPresenter", scrollView) as ScrollContentPresenter;
if (null == scrollContent) return;
scrollContent.AdornerLayer.Visibility = Visibility.Hidden;
};
}
}
}
模型的实现:
public Model()
{
if (Vorname == null)
Vorname = "";
...
errorsByPropertyName = new Dictionary<string, List<string>>();
this.PropertyChanged += Model_PropertyChanged;
ForceRevalidation(null);
}
private string _vorname;
public string Vorname { get => _vorname; set => SetField(ref _vorname, value); }
...
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
private Dictionary<string, List<string>> errorsByPropertyName;
public void ForceRevalidation(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
{
foreach (PropertyInfo property in GetType().GetProperties())
{
ValidateProperty(property.Name);
}
}
else
{
ValidateProperty(propertyName);
}
}
protected virtual void OnErrorsChanged(string propertyName)
{
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
OnPropertyChanged(nameof(HasErrors));
}
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public bool HasErrors => errorsByPropertyName.Any();
public System.Collections.IEnumerable GetErrors(string propertyName)
{
if (propertyName == null)
propertyName = "";
return errorsByPropertyName.ContainsKey(propertyName) ? errorsByPropertyName[propertyName] : null;
}
private void Model_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
ValidateProperty(e.PropertyName);
}
protected virtual void ValidateProperty(string propertyName)
{
if (propertyName == null)
propertyName = "";
ClearErrors(propertyName);
switch (propertyName)
{
case nameof(Vorname):
if (string.IsNullOrWhiteSpace(Vorname))
AddError(propertyName, propertyName + " is empty");
break;
...
default:
break;
}
}
protected void AddError(string propertyName, string error)
{
if (!errorsByPropertyName.ContainsKey(propertyName))
errorsByPropertyName[propertyName] = new List<string>();
if (!errorsByPropertyName[propertyName].Contains(error))
{
errorsByPropertyName[propertyName].Add(error);
OnErrorsChanged(propertyName);
}
}
protected void ClearErrors(string propertyName)
{
if (errorsByPropertyName.ContainsKey(propertyName))
{
errorsByPropertyName.Remove(propertyName);
OnErrorsChanged(propertyName);
}
}
我从我更大的 Model-Base-Class 中创建了这个最小的例子,希望我在这里得到了这方面的所有重要信息。