0

What is the possible reason whereby the validation is not working?

public class DatabaseObj : ValidatableModel, IFormattable
{
    [Required(ErrorMessage="Hostname is required")]
    public string Hostname
    {
        get { return _hostname; }
        set { SetProperty(ref _hostname, value); }
    }
}

[Serializable]
public abstract class ValidatableModel : Model, INotifyDataErrorInfo
{
}

[Serializable]
public abstract class Model : INotifyPropertyChanged
{
}

In xaml,

<TextBox Text="{Binding DatabaseObj.Hostname, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=true, NotifyOnValidationError=true}" 
             Grid.Column="1" Grid.Row="1" Margin="0,1,91,10" HorizontalAlignment="Stretch"/>

However, when I compile and run, I empty the textbox and no error message is shown and color still remain same.

*Update for Object class

king jia
  • 692
  • 8
  • 20
  • 43

1 Answers1

0

There is no default support for DataAnnotations in WPF. There are two ways to implement validation in WPF.

  1. Use exception based validation. In data binding expression you can turns on validation on exception like in the code below:

    <TextBox Name=«age» Grid.Row=«1» Grid.Column=«1» Width=«200» Margin=«5» Text="{Binding Path=Age, ValidatesOnExceptions=true, NotifyOnValidationError=true, UpdateSourceTrigger=PropertyChanged}" />
    

    Then, in your model you can use default logic of data type and it will validate input values (foe example, it'll prevent to set non-numeric values for Int32 type). Or you can add your custom logic by using Exceptions in property setter:

    public int Age 
    { 
        get { return age; }
        set
        {
            if(value < 0)
                throw new ArgumentException("Age can't be less then zero");
            if(value > 30)
                throw new ArgumentException("Huh, no, too old for me");
            age = value;
            OnNotifyPropertyChanged();
        }
    }
    
  2. Implement IDataErrorInfo in your class. There is a guide on MSDN.

    public string Error
    {
        get
        {
            return null;
        }
    }
    
    public string this[string name]
    {
        get
        {
            string result = null;
    
            if (name == "Age")
            {
                if (this.age < 0)
                {
                    result = "Age can't be less then zero";
                }
                if(this.age > 30)
                {
                    result = "Huh, no, too old for me";
                }                   
            }
            return result;
        }
    }
    

There are many articles (1, 2) in the internet to enable validation with DataAnnotations then you can add packages from this articles and modify your code to implement your scenario.

Vadim Martynov
  • 8,602
  • 5
  • 31
  • 43