Change default error message when enter non digit in a textbox requires integer

678 views Asked by At

I have a WPF application using MVVM. It has a textbox which needs an integer. The XAML of that text box is as below

<TextBox Name="textBoxElementWeight" 
    Text="{Binding ElementName=listBoxElement, Path=SelectedItem.Weight,
    UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
    Validation.ErrorTemplate="{StaticResource ValidationTextBoxTemplate}"/>

The view model implements interface INotifyDataErrorInfo.

When I delete the text to enter a new one, it says "Value '' could not be converted."

How do I change this error message to mine? Ex: "Please enter a number."

The whole Visual Studio solution can be downloaded here

1

There are 1 answers

4
Sheridan On

The simplest way to provide custom validation messages is to implement either the IDataErrorInfo Interface or the INotifyDataErrorInfo Interface in your data object class. I won't go into a detailed implementation here because there are many tutorials that are easily found online, however, I'll explain briefly.

When implementing the IDataErrorInfo Interface, you have an indexer property that you need to implement that takes in a string property name. It can be used like this:

public override string this[string propertyName]
{
    get
    {
        string error = string.Empty;
        if (propertyName == "Name" && Name.IsNullOrEmpty()) error = "You must enter the Name field.";
        else if (propertyName == "Name" && Name.Length > 100) error = "That name is too long.";
        ...
        return error;
    }
}

When implementing the INotifyDataErrorInfo Interface, you use DataAnnotation attributes on each property, like this:

[Required(ErrorMessage = "You must enter the Name field.")]
[StringLength(100, ErrorMessage = "That name is too long.")]
public string Name
{
    get { return name; }
    set { if (value != name) { name = value; NotifyPropertyChanged("Name", "Errors"); } }
}

Please search online for further information on implementing these interfaces.