3

问题标题几乎解释了我想要做的事情。

出于示例目的简化我的代码:

示例 WCF 服务的位:

    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 的位:

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

当我的数据注释被违反时,如何让我的视图执行某些操作?

我可以在这里和其他地方找到的所有示例要么不完全是我正在寻找的,要么与 ASP.NET 有关。我对 WPF 和数据注释知之甚少,而且我对 WCF 非常熟悉。

我已经尝试实现 IDataErrorInfo 接口,但我似乎无法在其中触发任何东西。我在 StackOverflow 上的另一个不同问题中找到了这段代码。我在 WCF 服务的 Restaurant 类中实现了这一点。

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

1 回答 1

1

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

于 2012-04-09T06:21:06.957 回答