我有一个名为 UniqueNameSolidWoodRule 的子类 ValidationRule 来验证数据网格中的重复条目。
这是代码:
public class UniqueNameSolidWoodRule : ValidationRule
{
public CollectionViewSource CurrentCollection { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (value != null)
{
ObservableCollection<SolidWood_VM> castedCollection = (ObservableCollection<SolidWood_VM>)CurrentCollection.Source;
foreach (SolidWood_VM swVM in castedCollection)
{
if (swVM.Designation == value.ToString())
{
return new ValidationResult(false, ResourcesManager.Instance.GetString("DuplicatedRecord"));
}
}
}
return new ValidationResult(true, null);
}
}
这是 XAML 片段:
<DataGrid.Resources>
<CollectionViewSource x:Key="CurrentSolidWoodCollection" Source="{Binding Path=SolidWoods}" />
</DataGrid.Resources>
<DataGridTextColumn x:Name="Column2" Header="{x:Static p:Resources.Designation}" Width="auto">
<DataGridTextColumn.Binding>
<Binding Path="Designation" ValidatesOnDataErrors="True" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<my:UniqueNameSolidWoodRule CurrentCollection="{StaticResource CurrentSolidWoodCollection}"/>
</Binding.ValidationRules>
</Binding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
我的问题是,有时这条规则会将值与它自己的行进行比较。我怎么能防止这种情况?在我看来,我需要一个与要比较的值关联的 row.index 属性,但不幸的是我无法找到实现这一目标的方法。