Benutzer:MovGP0/WinForms/Validation

aus Wikipedia, der freien Enzyklopädie
Zur Navigation springen Zur Suche springen
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      


WinForms Validation

[Bearbeiten | Quelltext bearbeiten]
View
    public partial class MainWindow
    {
        [Inject]
        public MainWindowViewModel ViewModel
        {
            get { return (MainWindowViewModel)DataContext; }
            set { DataContext = value; }
        }
 
        public MainWindow()
        {
            InitializeComponent();
        }
    }
ViewModel
    public class MainWindowViewModel : IDataErrorInfo
    {
        [Inject]
        public AbstractValidator<MainWindowViewModel> Validator { get; set; }
 
        public string Name { get; set; }
 
        #region IDataErrorInfo Members
        string IDataErrorInfo.Error
        {
            get
            {
                return Validator != null
                    ? string.Join(Environment.NewLine, Validator.Validate(this).Errors.Select(x => x.ErrorMessage).ToArray())
                    : string.Empty;
            }
        }
 
        string IDataErrorInfo.this[string propertyName]
        {
            get
            {
                if (Validator != null)
                {
                    var results = Validator.Validate(this, propertyName);
                    if (results != null
                        && results.Errors.Count() > 0)
                    {
                        var errors = string.Join(Environment.NewLine, results.Errors.Select(x => x.ErrorMessage).ToArray());
                        return errors;
                    }
                }
                return string.Empty;
            }
        }
        #endregion
    }