How do I correctly use .NET Data Annotations to validate data in WPF using the WCF backend?

The title of the question pretty much explains what I am trying to do.

Simplifying my code like:

WCF Service Sample Bits:

    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);
         }
    }

      

XAML example bits:

    <TextBox name="txt1" Text="{Binding Restaurant.Name, ValidatesOnDataErrors=True}"/>

      

How do I make my view something when the annotation of my information is broken?

All the examples I can find here and elsewhere are either not exactly what I'm looking for or that are related to ASP.NET. I don't know enough about WPF and Data Annotations and I am very green with WCF.

I tried to implement the IDataErrorInfo interface, but I can't get it to trigger anything. I found this code in another question on StackOverflow. I have implemented this in my Restaurant class in a 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;
    }

      

+3


source to share


1 answer


Classes to be linked in XAML must inherit from the INotifyDataErrorInfo or IDataErrorInfo interface. As far as I know, INotifyDataErrorInfo doesn't exist in WPF (4), but only in Silverlight and .Net 4.5.

To answer your question, your class must inherit from IDataErrorInfo in order for WPF to react to an error (any error) in your class. So you must have

public class Restaurant : IDataErrorInfo
{...}

      



Completed. Server classes can be annotated with the ValidationAttribute, but this won't leak if you just add the Service Reference. If you can exchange DLLs with client and service, then you should have a working solution if your class inherits from IDataErrorInfo.

You can see an example here

+1


source







All Articles