2009-08-06 63 views
1

在Silverlight 3中,我正在使用MVVM以及验证原则,即验证错误发生时设置人员会引发异常。我使用绑定语法上使用的字段双向即:如何将关闭按钮添加到Silverlight中的ValidationSummary

<TextBox x:Name="TextBoxClientName" Text="{Binding Name,Mode=TwoWay,ValidatesOnExceptions=True,NotifyOnValidationError=true}" Grid.Column="1" Grid.Row="0" Margin="5 5 5 5" /> 

我使用注解验证在视图模型这个属性:

[Required(ErrorMessage = "Name is required")] 
public string Name 
{ 
    get 
    { 
     return _client.Name; 
    } 
    set 
    { 
     Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "Name", DisplayName="Client Name" }); 
     _client.Name = value; 
    } 
} 

我有验证总结和所有的工作很好,但笑时,我正在寻找的功能如下:

你有数据表单,我希望验证摘要只出现在顶部,当我点击保存,并进一步我想实现关闭按钮上的那个ValidationSummary所以用户可以继续输入改正和修正。

我不知道如何控制验证摘要的可见性或切换,我已经尝试了可见性。以下是代码,我试过,这并收集关于报送错误,但我不能将其应用到在ValidationSummary:

public void Save() 
    { 
     List<ValidationError> errors = new List<ValidationError>(); 

     foreach (UIElement ui in LayoutRoot.Children) 
     { 
      FrameworkElement fe = ui as FrameworkElement; 

      if (fe != null) 
      { 
       foreach (ValidationError ve in Validation.GetErrors(fe)) 
       { 
        errors.Add(ve); 
       } 
      } 
     } 


     if (errors.Count > 0) 
     { 

      Validation1.DataContext = errors; 
      Validation1.Filter = ValidationSummaryFilters.All; 
     } 
     else 
     { 
      if (Saved != null) 
       Saved(this, EventArgs.Empty); 
     } 

    } 

干杯,

安德鲁

回答

1

我想,现在你”在您的应用程序中重新使用SIlverlight 4。 所以这个答案是为Silverlight 4

使用Silverlight 4的新接口加入INotifyDataError有3种方法:

public interface INotifyDataErrorInfo 
{ 
    // Returns True if the object has at least one property-level or top-level error. 
    bool HasErrors { get; } 

    // Returns the current set of property-level errors for the provided property name, or 
    // the current top-level errors if the argument is null or empty. 
    IEnumerable GetErrors(string propertyName); 

    // Raised when the set of errors for a particular property has changed, or when the 
    // top-level errors have changed. 
    event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged; 
} 

有一个关于该接口以及如何使用它的网络上大量文件。

如果您不想使用,则不必使用DataAnotations。但是,如果这样做,仍然可以使用System.ComponentModel.DataAnnotations名称空间中的Validator类获得验证错误。

如果你让你的ViewModel实现INotifyDataError并且还有一个属性(在ViewModel中)bool IsValidating或类似的东西。然后,每次属性更改时,都会触发您想要验证的所有属性的ErrorsChanged事件(您可以使用反射来获取属性名称)。那就是它。

现在你只需要制作IsValidating = false然后当请求保存时显示错误IsValidating = true

,你可以做其他的事情(,而这将在Silverlight 3中工作)被绑定在ValidationSummary到IsValidating财产(使用的IValueConverter)的可见性,然后从视图模型进行控制。