在我的应用程序中,我有一个非常大的DataGrid
,有几个DataGridTemplateColumn
个。在DataGrid
的资源中,DataGridRow
有一种样式。这种风格看起来像:
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsDirty}" Value="True">
<Setter Property="FontWeight" Value="Bold"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsEditing}" Value="True">
<Setter Property="AttachedProperties:DataGridExtensions.FocusOnEditingColumn" Value="{Binding IsEditing}"/>
</DataTrigger>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
在我的ViewModel
中,我订阅了PropertyChanged
- DataGrid
的ItemsSource中包含的DataObjects事件。因此,如果调用PropertyChanged-Event并且propertyname等于&#34; IsEdit&#34;我会对DataGrid
中的所有行进行一些验证。我可以使用以下方法:
private void CheckConsistence()
{
foreach (Module module in SelectedGroup.Modules)
{
string currentTarget = ResolveTargetPath(module);
foreach (Module toCompare in SelectedGroup.Modules.Except(new[] { module }))
{
string toCompareTarget = ResolveTargetPath(toCompare);
if (string.Compare(currentTarget, toCompareTarget, StringComparison.InvariantCultureIgnoreCase) == 0)
{
module.IsInvalid = true;
ValidationAdvices.Add(new ValidationAdvice("Duplicated path"));
}
}
}
}
如果Module-Object中的IsInvalid-Property设置为true,则更改Error-Object。 Module-Object的一部分如下所示:
public class Module : INotifyPropertyChanged, IDataErrorInfo
{
private bool isEditing;
public bool IsEditing
{
get { return isEditing; }
set
{
isEditing = value;
OnPropertyChanged(() => IsEditing);
}
}
private bool isInvalid;
public bool IsInvalid
{
get { return isInvalid; }
set
{
isInvalid = value;
if (isInvalid)
{
error = "Error";
}
else
{
error = null;
}
OnPropertyChanged(() => IsInvalid);
OnPropertyChanged(() => Error);
}
}
public string this[string columnName]
{
get { return string.Empty; }
}
private string error;
public string Error
{
get { return error; }
}
}
我的DataGrid
有RowValidationErrorTemplate
,如下所示:
<ControlTemplate x:Key="RowErrorTemplate" TargetType="Control" x:Shared="False">
<Grid ClipToBounds="False" Panel.ZIndex="10000">
<AdornedElementPlaceholder Name="adornedElement"/>
<Image HorizontalAlignment="Center" VerticalAlignment="Center" Width="16" Height="16"
Source="pack://application:,,,/MyApp.UI.Resources;component/Graphics/Error_16x16.png"
ToolTipService.IsEnabled="True"
ToolTipService.ShowOnDisabled="True"
ToolTip="{Binding Converter={converters:ModuleValidationErrorConverter}}"/>
</Grid>
</ControlTemplate>
我现在的问题是,如果两行具有相同的路径,则两行应显示为错误行。但只有一行会获得DataGridRow
样式中的errortemplate和red-background。每行调用ValidationAdvices.Add(new ValidationAdvice("Duplicated path"));
。我必须做什么才能让每一行都获得验证者的转换?
我也将DataGrid.RowValidationRules
设置为:
<DataGrid.RowValidationRules>
<DataErrorValidationRule ValidatesOnTargetUpdated="True" ValidationStep="UpdatedValue"/>
</DataGrid.RowValidationRules>