Wpf datagrid validationrule for unique field

試著忘記壹切 提交于 2019-12-05 17:10:57

I finally got things working!

Here's the solution:

In the XAML I added the following ValidationStep:

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

This way I'm getting a BindingExpression object instead of a string as the first parameter of the overridden Validate method, which gives me much more information about the record to validate like the HashCode I can use to check if I'm comparing the same object.

Here's the updated Validate method:

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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!