locked
MVVM Input validation and button RRS feed

  • Question

  • I'm new in MVVM so bare with me! Here's the scenario.

    On a dialog window of my application, a textbox is validated with a ValidationRule class:

    public class ImgPathValidator : ValidationRule
        {
            //Validates a string as the path of an accepted image
            string[] extensions = { ".bmp", ".jpg", ".jpeg", ".gif", ".png" };
            public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
            {
                if (value.ToString().Length != 0)
                {
                    try
                    {
                        FileInfo fi = new FileInfo(value.ToString());
                        if (fi.Exists == true)
                        {
                            if (extensions.Contains(fi.Extension) == false)
                                return new ValidationResult(false, "The file is not an accepted image!");
                        }
                        else
                            return new ValidationResult(false, "The file doesn't exist!");
                    }
                    catch (Exception ex)
                    {
                        return new ValidationResult(false,ex.Message);
                    }  
                }
                else
                    return new ValidationResult(false, "You must give an image path!");
    
                return new ValidationResult(true, "");
            }
        }
    

    On the same window, a button is bound to a RelayCommand (thanks Josh Smith!):

    public ICommand DoGetName
            {
                get
                {
                    if (_DoGetName == null)
                        _DoGetName = new RelayCommand(param => DoGetName_Execute(),
                                                                                  param => DoGetName_CanExecute());
                    return _DoGetName;
                }
            }
    


    This command, along with the Execute and CanExecute methods, are placed in the ViewModel of the window.

    The question is this: how can I disable/enable the button based on validation error in the textbox?

     

    If a relative question has already been answered, please point me to it. Thanks in advance.

     

    PS: I also have a question on handling Dialogs with MVVM but all in due time!

    Monday, October 3, 2011 6:58 PM

Answers

All replies