3
votes

I have a WPF DataGrid with RowValidationRules. I would like to set the focus or begin editing a specific cell in case a validation fails.

For example, if the value in a cell has be lower than the value in another cell and the user does not respect this rule, I would like to automatically set the focus and begin editing the first cell.

What is the most elegant way to do this? I noticed that the ValidationResult.ErrorContent property is usually used to display an error message, but since it is of type "object", maybe I could customize it to return information about the cell that should get the focus in case of a validation error? I'm not sure how to recover and use that information in XAML though.

1

1 Answers

0
votes

Since ValidationRule does not inherit from DependencyObject, you can't define a DependencyProperty in your custom ValidationRule class and bind it to the proper UI element.

however I can think of a solution that helps you solve the problem:

you can still define a string property (say TargetUINameString) in your custom ValidationRule class and set it to the name of each UI Element like this:

<TextBox Name="textbox1"...
     <c:MyValidationRule TargetUINameString="textbox1"/>
...

add a static property (say ActiveInstanceOfThis) to your window from, which grants you the access to the active instance of the window class. (set it to this in your window's constructor)

then resolve it using FindName:

public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
    if (value==null)
    {
        var uielement = 
            Window1.ActiveInstanceOfThis.stackPanel1.FindName(TargetUINameString)
            as TextBox;
        if(uielement!=null) uielement.Focus();
    }
}

it's a bit dirty but it works!