i was wondering how to best validate some user inputs on the WPF mvvm pattern? I've implemented IDataErrorInfo in my ViewModel. But I don't know how to use this interface with raising an exception. My purpose is to not have any logic in my viewModel. So the validation has to be in the business logic class.
The bounded field is the Property "Name" in my ViewModel. It is
ValidatesOnDataErrors=True
The Property in my viewmodel looks like this:
//Property in ViewModel
public string Name
{
get
{
return myBl.Name;
}
set
{
try
{
myBl.Name = value;
}
catch(InvalidCastException e)
{
Console.WriteLine(String.Format("Es ist eine Exception aufgetreten: {0}", e.Message));
}
}
}
The businesslogic lookes like that:
//BusinessLogic Class
public string Name
{
get { return name; }
set
{
if (value.Contains('1'))
throw new InvalidCastException("Cannot contain 1");
name = value;
}
}
The Exception is thrown as proposed but how to move on? I want the e.Message to be the ValidationErrorMessage
.
The only examples i found were with validation in
public string this[string propertyName]
{
get
{ throw new NotImplementedException()}
}
But it not seems to be the doable way with exceptions.
Don't catch any exceptions in the ViewModel properties:
public string Name
{
get
{
return myBl.Name;
}
set
{
myBl.Name = value;
}
}
and check the ValidateOnExceptions option in the data binding dialog (or ValidatesOnExceptions=True
in the XAML code).