WPF DataGrid的有效性规则的唯一字段(Wpf datagrid validationrul

2019-09-17 04:11发布

我有一个名为UniqueNameSolidWoodRule验证DataGrid中重复的条目suclassed有效性规则。

下面的代码:

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属性,但unfortunnally我不出路来实现这一目标。

Answer 1:

我终于得到了事情的工作!

这里的解决方案:

在XAML添加以下ValidationStep:

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

这样,我得到一个BindingExpression对象,而不是一个字符串作为覆盖验证方法的第一个参数,这给了我关于记录更多的信息来验证像哈希码 ,我可以用它来检查,如果我比较同一对象的。

下面是更新验证方法:

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);
    }
}


文章来源: Wpf datagrid validationrule for unique field