开发者

How can I find out the validation status of a Silverlight usercontrol?

I have a Silverlight usercontrol with a few fields on it that are bound via RIA services to a database. I am using NotifyOnValidationError=true, ValidatesOnExceptions=true on these fields and a ValidationSummary control to show any errors with the fields. This all works开发者_如何转开发 fine.

However, on the usercontrol I have a "Save" button that will call context.SubmitChanges() when clicked. The problem is that this button can be clicked (and so SubmitChanges called )even when there are still errors present.

How do I determine whether there are validation errors still present, or is there anyway of binding the IsEnabled property of the Save button to the validation status?


To stop the save button being available when there are client side validation errors still in effect you could try this.

In your class (code behind or view model) you will have something that provides the current instance of a RIA entity you are working with.

public SampleRIAEntity SelectedEntity { get; set; }

Using this extension method:

public static class RiaExtensions
{
  public static bool CheckValidation<T>( this T riaEntity ) where T : Entity
  {
    ValidationContext vc = new ValidationContext( riaEntity, null, null);
    ICollection<ValidationResult> validationResults = new List<ValidationResult>();
    return ( Validator.TryValidateObject( riaEntity, vc, validationResults ) == true );
  }
}

You could provide a property to use with the IsEnabled on the Save button.

public bool HasErrors
{
  get
  {
    return SelectedEntity.CheckValidation<SampleRIAEntity>();
  }
}

This would then run through all the validation rules available on the client side. The save could still not commit if there are server side rules which weren't satisfied.


You can bind the IsEnabled property of the save button to the ValidationSummary control's HasErrors field. This will disable the button as long as the validation summary is visible. You'll need to use a converter to invert the value of HasErrors 

Here's the XAML: 

    <UserControl .... > 
       <UserControl.Resources> 
           <Converters1:NotBoolConverter x:Key="NotBoolConverter" />
        </UserControl.Resources> 

        <Button IsEnabled="{Binding HasErrors, ElementName=valSummary, Converter={StaticResource NotBoolConverter}}" /> 

Here's the code for the NotBoolConverter: (from http://forums.silverlight.net/forums/p/78115/184444.aspx)

internal class NegationConverter : IValueConverter
{
    #region IValueConverter Members 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { var b = (bool) value; return !b; } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    { throw new NotImplementedException(); } 
    #endregion 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜