WPF Datagrid的新行验证 [英] WPF Datagrid new row validation

查看:380
本文介绍了WPF Datagrid的新行验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个简单的WPF应用程序的DataGrid wchich被绑定到列表Employee对象:

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;
        }
    }

正如你所看到的,我想prevent创造员工没有设置名称属性。 所以,我做了一个验证规则:

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);
    }
}

在XAML的名称字段如下:

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>

如果我尝试编辑现有员工行的名称DataGrid中,并将其设置为空字符串,数据网格标志着错误的领域,并且不允许保存一行。这是正确的行为。

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.

但是,如果我创建一个新的行和preSS输入键盘,这个新行与_name设置为NULL创建和验证不起作用。我想这是因为DataGrid中调用默认构造新的行对象,并设置_name字段设置为NULL。

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?

推荐答案

您可以实施 IDataError 员工目的。有一个关于这个 rel="nofollow">一个很好的页面。

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

这篇关于WPF Datagrid的新行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆