DataGrid行验证基于其他行

时间:2017-03-29 09:24:07

标签: c# wpf xaml mvvm

我想根据同一DataGridCell中其他DataGridRows的值验证DataGrid。但是在我继承的MyValidationRule对象中,我无法访问DataGrid的所有绑定项,只能访问当前行。

如何在Validate()的{​​{1}}方法中访问DataGrid的其他绑定项?

2 个答案:

答案 0 :(得分:0)

您可以向自定义ValidationRule类添加依赖项属性,并将此属性绑定到DataGrid

虽然需要一些努力。您需要创建一个派生自DependencyObject的包装类,并使用DataContext捕获Freezable。以下TechNet文章对此进行了解释。请参考它。

WPF:将数据绑定值传递给验证规则: https://social.technet.microsoft.com/wiki/contents/articles/31422.wpf-passing-a-data-bound-value-to-a-validation-rule.aspx

答案 1 :(得分:0)

您想要做什么我认为遵循可视化树直到DataGrid并从那里访问ItemsSource来执行验证。像这样......

public class SampleRowValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        BindingGroup bg = value as BindingGroup;
        if (bg != null && bg.Items.Count > 0)
        {
            DataGridRow dgrow = bg.Owner as DataGridRow;
            if(dgrow != null)
            {
                DataGrid dg = GetParent<DataGrid>(dgrow);
                // ... add more
            }
        }
        return new ValidationResult(true, null);
    }
    private T GetParent<T>(DependencyObject d) where T : class
    {
        while (d != null && !(d is T))
        {
            d = VisualTreeHelper.GetParent(d);
        }
        return d as T;

    }
}
相关问题