Rewrap Evil ValidationErrors in WPF ValidationRule to enable ajax like validation on WPF Form

We use Evil Attribute library in our service and UI/ViewModel to do validation on DTO, the big advantage is centralizing the validation rules. One challenge left is how to enable WPF Forms dynamically showing the error message, like ajax doing on web.

Found a very smart and simple solution for this, what we need to do is simply to wrap the Evil ValidationErrors in WPF ValidationRule class.

<Window.Resources>
 <ControlTemplate x:Key="TextBoxErrorTemplate">
 <StackPanel>
 <StackPanel Orientation="Horizontal">
 <Image Height="16" Margin="0,0,5,0"
 Source="warning_48.png"/>
 <AdornedElementPlaceholder x:Name="Holder"/>
 </StackPanel>
 <Label Foreground="Red" Content="{Binding ElementName=Holder,
 Path=AdornedElement.(Validation.Errors)&#91;0&#93;.ErrorContent}"/>
 </StackPanel>
 </ControlTemplate>
 </Window.Resources>
 <Grid>
    ...

  <TextBox Height="23" Margin="35,9,77,0" Name="textBox1" VerticalAlignment="Top"
     KeyUp="OnTextBoxKeyUp"
     Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}">
     <TextBox.Text>
    <Binding ElementName="listBox1" Path="SelectedItem" UpdateSourceTrigger="PropertyChanged">
      <Binding.ValidationRules>
        <ViewModels:EmailRoleRule />
      </Binding.ValidationRules>
    </Binding>
  </TextBox.Text>
 </TextBox>


public class EmailRoleRule : ValidationRule
 {
  public override ValidationResult Validate(object value, CultureInfo cultureInfo)
   {
   var roleName = (string) value;
   var validator = new EvilValidator(new EmailRoleDto() { Name = roleName });
   if (validator.IsValid())
   {
    return new ValidationResult(true, null);
   }
   return new ValidationResult(false, string.Join("\n", validator.ValidationErrors.ToArray()));
  }
 }

wpf_validation

This technoque is actually described on MSDN.

Here is a post talking about the same skill but takes advantage of tooltips, pretty close to CSLA content control.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s