Search code examples
wpfvalidationdata-bindingdatagridcell

validate cell value based on other other property of this data item


I have a DataGrid and it has a DataGridTextColumn that has items which I want to validate based on other cell's value in the same row. The column is bound to one of data item's property. Another property of same data item contains something like an input mask. Validation should check new value with the input mask for current row's data item. That input mask is not edited anywhere on the form (no need to track the input mask changes), but the input mask can be different for each row. So how do I write a custom validator like that? I've tried the following:

<DataGridTextColumn Width="*">
                    <DataGridTextColumn.Binding>
                        <Binding Path="Name" Mode="TwoWay" UpdateSourceTrigger="LostFocus" ValidatesOnExceptions="True" NotifyOnValidationError="True" ValidatesOnDataErrors="True">
                            <Binding.ValidationRules>
                                <validation:Class2 ValidatesOnTargetUpdated="True" Format="999" />
                            </Binding.ValidationRules>
                        </Binding>
                    </DataGridTextColumn.Binding>
                </DataGridTextColumn>

And here goes validator code:

 class Class2 : ValidationRule
    {        
        /// <summary>
        /// input mask
        /// </summary>
        public string Format { get; set; }

    /// <param name="value">cell's new value that should be validated against input mask</param>        
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        // validation logic goes here
        return new ValidationResult(true, null);
    }
}

But it appears that I can't bind Class2.Format property to the data item because Class2 doesn't inherit from DependencyObject. I think that I might solve this problem if I simply init all Format values manually from C# code, but I think that there should be better solutions using XAML binding expressions.

Any ideas?


Solution

  • I should use something other ValidationStep="RawProposedValue", then I will be getting BindingExpression as a value parameter at my Validate method, and this BindingExpression.DataItem property contains actual data item that I am looking for.