views:

192

answers:

2

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

Business entity:

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 file:

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

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

DataContext = new Person();

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?

+1  A: 

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;
        }
    }
}
Stanislav Kniazev
Yes, I can, but I'd like to tune up WPF binding rather then change my business entities. Since I am not WPF expert, a hope there is relatively easy solution of such problem. It seems to be typical behavior - not to show alerts for all field when form is just open.
Alex Kofman
Stanislav Kniazev
A: 

There is another solution which i found but i dont like it alot. You have to clear validation on page load.

What i mean is you have to do this : Validation.ClearInvalid(...) for instance if you have a textbox you dont want to be validated should call

Validation.ClearInvalid(txtSomething.GetBindingExpression(TextBox.TextProperty)) or something like that.

You should do this for every control you want to be cleared of validation.

I didnt like the solution but that was the best i found. I hoped wpf had something "out of the box" that worked but didnt find it.

6lix