Wpf datagrid validationrule用于唯一字段

时间:2012-05-11 08:54:48

标签: wpf validation wpfdatagrid

我有一个名为UniqueNameSolidWoodRule的VeridationRule,用于验证数据网格中的重复条目。

以下是代码:

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属性,但遗憾的是我无法找到实现这一目标的方法。

1 个答案:

答案 0 :(得分:12)

我终于让事情奏效了!

以下是解决方案:

在XAML中,我添加了以下ValidationStep:

<my:UniqueNameSolidWoodRule CurrentCollection="{StaticResource CurrentSolidWoodCollection}" ValidationStep="CommittedValue"/>

这样我得到一个BindingExpression对象而不是字符串作为被覆盖的Validate方法的第一个参数,这给了我更多关于要验证的记录的信息,比如我可以使用的 HashCode 检查我是否正在比较同一个对象。

这是更新的验证方法:

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;

            SolidWood_VM curValue = (SolidWood_VM)((BindingExpression)value).DataItem;

            foreach (SolidWood_VM swVM in castedCollection)
            {
                if (curValue.GetHashCode() != swVM.GetHashCode() && swVM.Designation == curValue.Designation.ToString())
                {
                    return new ValidationResult(false, ResourcesManager.Instance.GetString("DuplicatedRecord"));
                }
            }
        }

        return new ValidationResult(true, null);
    }
}