如何燮preSS验证时,没有进入preSS

2023-09-03 08:36:05 作者:局外人

我使用实现 IDataErrorInfo 接口WPF数据与实体的结合。一般我code是这样的:

I use WPF data binding with entities that implement IDataErrorInfo interface. In general my code looks like this:

商业实体:

public class Person : IDataErrorInfo 
{
  public string Name { get; set;}

  string IDataErrorInfo.this[string columnName]
  {
    if (columnName=="Name" && string.IsNullOrEmpty(Name))
      return "Name is not entered";
    return string.Empty;
  }  
}

XAML文件:

Xaml file:

<TextBox Text="{Binding Path=Name, Mode=TwoWay, ValidatesOnDataErrors=true}" />

当用户点击创建新的人以下code执行:

When user clicks on "Create new person" following code is executed:

DataContext = new Person();

现在的问题是,这只是创造人的时候它的名称是空的和WPF的立即绘制红色边框,并显示错误信息。我希望它只是显示错误时的名字已经被编辑,焦点将丢失。有谁知道这样做的方法是什么?

The problem is that when person is just created its name is empty and WPF immediately draws red frame and shows error message. I want it to show error only when name was already edited and focus is lost. Does anybody know the way to do this?

推荐答案

您可以更改您的个人类射击验证错误只有名称属性已发生更改:

You can change your person class to fire validation error only if Name property was ever changed:

public class Person : IDataErrorInfo {

    private bool nameChanged = false;
    private string name;
    public string Name {
        get { return name; }
        set { 
            name = value;
            nameChanged = true;
        }
    }

//... skipped some code

    string IDataErrorInfo.this[string columnName] {
        get {
            if(nameChanged && columnName == "Name" && string.IsNullOrEmpty(Name)) 
                return "Name is not entered"; 
            return string.Empty;
        }
    }
}