Check ViewModel on button click

I have a ViewModel that implements IDataErrorInfo and master-detail-view. How can I call vaildation of the current ViewModel when the user clicks the save button in the detail view and not before?

+2


source to share


2 answers


Start by enabling the flag on your virtual machine and set it to false. In the Button command code (assuming you bind your button to a command in your virtual machine), enable the flag before running your validation code.

In the "get" code, in the IDataErrorInfo properties, return only a validation error if the flag is set to true, otherwise return an empty string.



Before toggling the flag back to false, throw PropertyChangedEvent with an empty string as the property name, this will cause the binding system to revise all bindings in the current context and also check for errors in IDataErrorInfo.

+4


source


benPearce gave a great answer.

As he noted.

  • have this[columnName]

    return null (even if the data is invalid) until you click "Save"
  • in the Save command you need to call OnPropertyChanged(null)

    for WPF to override the bindings (and poll the indexer)

Instead of using a flag, this example uses a dictionary to achieve the same result.




In View

<TextBox Text="{Binding Surname, ValidatesOnDataErrors=True}" />

      

In ViewModel

public string Surname { get; set; }

#region Validation
//http://blogs.msdn.com/b/bethmassi/archive/2008/06/27/displaying-data-validation-messages-in-wpf.aspx
Dictionary<string, string> validationErrors = new Dictionary<string,string>();

void Validate()
{
    validationErrors.Clear();
    if (srtring.IsNullOrWhitespace(Surname)) // Validate Surname 
    {
        validationErrors.Add("Surname", "Surname is mandatory.");
    }

    //http://stackoverflow.com/a/5210633/240835
    // Call OnPropertyChanged(null) to refresh all bindings and have WPF check the this[string columnName] indexer.
    OnPropertyChanged(null);
}

#region IDataErrorInfo Members
public string Error
{
    get 
    {
        if (validationErrors.Count > 0)
        {
            return "Errors found.";
        }
        return null;
    }
}

public string this[string columnName]
{
    get 
    {                
        if (validationErrors.ContainsKey(columnName))
        {
            return validationErrors[columnName];
        }
        return null;
    }
}

#endregion
#endregion
public void Save()
{
    Validate();
    if (validationErrors.Count == 0)
    {
        DoSave();
    }
}

      

+3


source







All Articles