ReactiveUI and Validation

南笙酒味 提交于 2019-12-07 02:55:45

For anyone else looking for an example on using ReactiveValidatedObject, here's what worked for me. Note that you'll have to add a reference to System.ComponentModel to your class as well.

public class MyViewModel: ReactiveValidatedObject
{
  public ReactiveAsyncCommand SaveMyDataCommand { get; protected set; }

  // THIS PROPERTY INDICATES WHETHER ALL FIELDS HAVE BEEN VALIDATED
  public bool IsSaveEnabled
  {
    get { return IsObjectValid(); }
  }

  private string _email;
  [ValidatesViaMethod(AllowBlanks=true,AllowNull=true,Name="IsEmailValid",ErrorMessage="Please enter a valid email address")]
  public string Email
  {
    get { return _email; }
    set
    {
      _email = value;
      raisePropertyChanged("Email");
      SendEmail = SendEmail;
      raisePropertyChanged("IsSaveEnabled");
    }
  }

  private string _name;
  public string Name
  {
    get { return _name; }
    set
    {
      _name= value;
      raisePropertyChanged("Name");
    }
  }

  private bool _sendEmail = false;
  [ValidatesViaMethod(Name = "IsSendEmailValid", ErrorMessage = "Make sure a valid email address is entered.")]
  public bool SendEmail
  {
    get { return _sendEmail; }
    set
    {
      _sendEmail = value;
      raisePropertyChanged("SendEmail");
      raisePropertyChanged("IsSaveEnabled");
    }
  }  

  public bool IsEmailValid(string email)
  {
    if (string.IsNullOrEmpty(email))
    {
      return true;
    } 

    // Return result of Email validation
  }

  public bool IsSendEmailValid(bool sendEmail)
  {
     if (sendEmail)
     {
       if (string.IsNullOrEmpty(Email))
       {
         return false;
       }

       // Return result of Email validation
     }
  }

  public MyViewModel()
  {
    SaveMyDataCommand = new ReactiveAsyncCommand(null, 1);
  }
}

I hope this helps someone! :)

Use ReactiveValidatedObject, then use Data Annotations (on phone, sorry for short message)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!