C# – WPF Datagrid new row validation

cdatagridnetvalidationwpf

I made a simple WPF application with DataGrid wchich is binded to the List with Employee objects:

public class Employee
{
    private string _name;

    public int Id { get; set; }


    public string Name
    {
        get { return _name; }
        set
        {
            if (String.IsNullOrEmpty(value))
                throw new ApplicationException("Name cannot be empty. Please specify the name.");
            _name = value;
        }
    }

As you can see, I want to prevent creating Employees without set Name property.
So, I made a validation rule:

public class StringValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        string str = value as string;
        if (String.IsNullOrEmpty(str))
            return new ValidationResult(false, "This field cannot be empty");
        else
            return new ValidationResult(true, null);
    }
}

The XAML for Name field is the following:

<DataGridTextColumn Header="Name" 
                                ElementStyle="{StaticResource datagridElStyle}" >
                <DataGridTextColumn.Binding>
                    <Binding Path="Name" Mode="TwoWay" NotifyOnValidationError="True" ValidatesOnExceptions="True" UpdateSourceTrigger="PropertyChanged" >
                        <Binding.ValidationRules>
                            <emp:StringValidationRule/>
                        </Binding.ValidationRules>
                    </Binding>
                </DataGridTextColumn.Binding>
            </DataGridTextColumn>

If I try to edit the name of existing employee row in DataGrid and set it to empty string, datagrid marks the wrong field and does not allow to save row. This is correct behavior.

But if I create a new row and press Enter on keyboard, this new row is created with _name set to NULL, and validation does not work. I guess this is because DataGrid calls default constructor for new row object and sets _name field to NULL.

What is the correct way of validation for new rows?

Best Answer

You could implement IDataError on your Employee object. There's a good page on this here.

Related Topic