Question title pretty much explains what I am trying to do.
Simplification of my code for example purpose:
Bits of an example WCF Service:
pulic class Restaurant
{
//RegEx to only allow alpha characters with a max length of 40
//Pardon if my regex is slightly off
[RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$")]
public string Name { get; set; }
}
public class RestaurantService
{
List<Restaurant> restaurants = new List<Restaurant>();
public AddRestaurant(string name)
{
Restaurant restaurant = new Restaurant();
restaurant.Name = name;
restaurants.Add(restaurant);
}
}
Bits of example XAML:
<TextBox name="txt1" Text="{Binding Restaurant.Name, ValidatesOnDataErrors=True}"/>
How do I make my view do something when my data annotation is violated?
All of the examples I can find here and elsewhere are either not exactly what I am looking for or that have to do with ASP.NET. I don't know enough about WPF and Data Annotations and I am very green with WCF.
I have tried implementing the IDataErrorInfo interface, but I can't seem to get anything to fire in it. I found this code in another different question on StackOverflow. I implemented this in my Restaurant class in the WCF service.
public string this[string columnName]
{
get
{
if (columnName == "Name")
{
return ValidateProperty(this.Name, columnName);
}
return null;
}
}
protected string ValidateProperty(object value, string propertyName)
{
var info = this.GetType().GetProperty(propertyName);
IEnumerable<string> errorInfos =
(from va in info.GetCustomAttributes(true).OfType<ValidationAttribute>()
where !va.IsValid(value)
select va.FormatErrorMessage(string.Empty)).ToList();
if (errorInfos.Count() > 0)
{
return errorInfos.FirstOrDefault<string>();
}
return null;
}