Reputation: 281
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;
}
Upvotes: 3
Views: 2223
Reputation: 3615
Classes that are to be bound in XAML must inherit from INotifyDataErrorInfo or IDataErrorInfo interface. To my knowledge, INotifyDataErrorInfo does not exist in WPF (4) but only in Silverlight and .Net 4.5.
To answer your question - your class must inherit from IDataErrorInfo to make WPF react where there is an error (any error) in your class. So you have to have
public class Restaurant : IDataErrorInfo
{...}
Implemented. Server classes can be annotated with ValidationAttribute but this will not flow if you simply add Service Reference. If you can share the DLL across the client and the service then you should have a working solution as long as your class inherits from IDataErrorInfo.
You can see an example here
Upvotes: 1