How to disable/enable a button while doing validation using IDataErrorInfo
?
I am using MVVM
using GalaSoft light Framework. In my Model class I have implemented IDataErrorInfo
to display the error messages.
public string this[string columnName]
{
get
{
Result = null;
if (columnName == "FirstName")
{
if (String.IsNullOrEmpty(FirstName))
{
Result = "Please enter first name";
}
}
else if (columnName == "LastName")
{
if (String.IsNullOrEmpty(LastName))
{
Result = "Please enter last name";
}
}
else if (columnName == "Address")
{
if (String.IsNullOrEmpty(Address))
{
Result = "Please enter Address";
}
}
else if (columnName == "City")
{
if (String.IsNullOrEmpty(City))
{
Result = "Please enter city";
}
}
else if (columnName == "State")
{
if (State == "Select")
{
Result = "Please select state";
}
}
else if (columnName == "Zip")
{
if (String.IsNullOrEmpty(Zip))
{
Result = "Please enter zip";
}
else if (Zip.Length < 6)
{
Result = "Zip's length has to be at least 6 digits!";
}
else
{
bool zipNumber = Regex.IsMatch(Zip, @"^[0-9]*$");
if (zipNumber == false)
{
Result = "Please enter only digits in zip";
}
}
}
else if (columnName == "IsValid")
{
Result = true.ToString();
}
return Result;
}
}
Screenshot: http://i.stack.imgur.com/kwEI8.jpg
How to disable/enable save button. Kindly suggest?
Thanks
Here is my way of doing it using a combination of IDataErrorInfo interface, ValidationErrors Dictionary, and MVVM-Light messaging system. Straight forward and works like charm:
Model Class
View Code Behind
you can add add a boolean property CanSave and set it at the end of your valiation method. Bind the IsEnabled from your button to IsValid. Somthing like this:
The Josh Smith Way of doing this is to create the following methods in the Model:
The ViewModel then contains a
CanSave
Property that reads theIsValid
property on the Model:Finally, if you are using
RelayCommand
, you can set the predicate of the command to theCanSave
property, and the View will automatically enable or disable the button. In the ViewModel:And in the View:
And that's it!
PS: If you haven't read Josh Smith's article yet, it will change your life.