Simple Validation in WPF

A very simple example of displaying validation error next to controls in WPF

Introduction

This is a simple example of validation in XAML for WPF controls and displaying error messages.

Background

I was looking for something out-of-the-box from WPF where no extra coding of style or template is needed for displaying validation errors, where we just need to code the validation logic for each control and it should automatically display an error icon or message next to the control. However, I did not find anything straightforward like that in WPF. But it can be achieved in two simple steps.

Using the Code

Here is a very simple form in XAML that is created which has three textbox controls:

Let us add code so that when values are entered in the above text boxes, they automatically run validation and if there are validation errors, they will be displayed next to the corresponding control. In order to do this, the following two steps are needed:

  1. Create a ControlTemplate with AdornedElementPlaceHolder
  2. Implement a validation class inheriting the abstract class called ValidationRule

Here is the sample validation control template. Let us start with a very simple validation control template where all we have is a TextBlock which will display a red exclamatory sign next to the control that has an error.

Collapse | Copy Code

<ControlTemplate x:Key="validationErrorTemplate">
    <DockPanel>
        <TextBlock Foreground="Red"
            DockPanel.Dock="Top">!</TextBlock>
        <AdornedElementPlaceholder
           x:Name="ErrorAdorner"
        ></AdornedElementPlaceholder>
    </DockPanel>
</ControlTemplate> 

Now, let us also create a validator class by inheriting from the ValidationRule class and implementing its abstract method as below:

Collapse | Copy Code

public class NameValidator : ValidationRule
{
    public override ValidationResult Validate
      (object value, System.Globalization.CultureInfo cultureInfo)
    {
        if (value == null)
            return new ValidationResult(false, "value cannot be empty.");
        else
        {
            if (value.ToString().Length > 3)
                return new ValidationResult
                (false, "Name cannot be more than 3 characters long.");
        }
        return ValidationResult.ValidResult;
    }
}

Let‘s plug this validation control template and the validation rule with control that we want to validate.

Collapse | Copy Code

<TextBox Height="23" HorizontalAlignment="Left"
              Grid.Column="1" Grid.Row="0" Name="textBox1"
              VerticalAlignment="Top" Width="120"
              Validation.ErrorTemplate="{StaticResource validationErrorTemplate}"
         >
    <TextBox.Text>
        <Binding Path="Name" Mode="TwoWay"
        UpdateSourceTrigger="LostFocus">
            <Binding.ValidationRules>
                <local:NameValidator></local:NameValidator>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox> 

When we run this now and enter a name longer than three characters long, it displays the red exclamatory sign indicating validation error.

Now let us just replace the TextBlock in the above validation control template code (the line that is in bold) with the StackPanel containing an ellipse and a TextBlock to display the same validation error, as below:

Collapse | Copy Code

<ControlTemplate x:Key="validationErrorTemplate">
    <DockPanel>
    <StackPanel Orientation="Horizontal" DockPanel.Dock="Top">
        <Grid Width="12" Height="12">
            <Ellipse Width="12" Height="12"
            Fill="Red" HorizontalAlignment="Center"
            VerticalAlignment="Center"

                     ></Ellipse>
            <TextBlock Foreground="White" FontWeight="Heavy"
            FontSize="8" HorizontalAlignment="Center"
            VerticalAlignment="Center" TextAlignment="Center"
                       ToolTip="{Binding ElementName=ErrorAdorner,
                       Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"
                       >X</TextBlock>
        </Grid>
        <TextBlock Foreground="Red" FontWeight="12" Margin="2,0,0,0"
                   Text="{Binding ElementName=ErrorAdorner,
                   Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"
                   ></TextBlock>
        </StackPanel>
        <AdornedElementPlaceholder
        x:Name="ErrorAdorner" ></AdornedElementPlaceholder>
    </DockPanel>
</ControlTemplate>

Now when we run the code and validation fails, a validation error will be displayedas shown in the screenshot below (coded validator class for age and phone number as well).

That is all that is needed for the simplest validation error to show up next to the control. Notice in the validation control template, we are using a DockPanel as the layout control, therefore we can easily change where the error icon and error message will be displayed. We can display them on top of the control that is failing validation (as the above picture), or on the left, right, or bottom.

时间: 2024-10-17 10:33:03

Simple Validation in WPF的相关文章

Reusable async validation for WPF with Prism 5

WPF has supported validation since the first release in .NET 3.0. That support is built into the binding object and allows you to indicate validation errors through exceptions, an implementation of the IDataErrorInfo interface, or by using WPF Valida

[WPF系列]-Data Validation

项目经常前台界面涉及到用户输入时,我们常常会用到数据有效性的验证.在网页中我们之前用js来校验Form中的数据有效性.在WPF中我们如何实现这种验证机制了?答案:INotifyDataErrorInfo   INotifyDataErrorInfo简介 如图示该接口有三件宝贝: HasErrors: a read-only boolean property which tells if the object as a whole have any validation errors; GetEr

WPF 验证没有通过无法保存数据(非常好)+ 虚似数据库

Validation control with a single validation rule is easy, but what if we need to validate a control using different validation rules. This article tells how to achieve multiple validation on single control in an easy and systematic way. Download sour

[WPF系列]-Prism+EF

  源码:Prism5_Tutorial       参考文档 Data validation in WPF WPF 4.5 – ASYNCHRONOUS VALIDATION Reusable async validation for WPF with Prism 5 Validating our ViewModel Implementing a Data Access Layer with Entity Framework 6.1 - Part1 Implementing a Data Ac

Learning JavaScript Design Patterns -- A book by Addy Osmani

Learning JavaScript Design Patterns A book by Addy Osmani Volume 1.6.2 Tweet Copyright © Addy Osmani 2015. Learning JavaScript Design Patterns is released under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 unported license. It

Struts2的ActionError&ActionMessage示例

本教程显示使用Struts2的 ActionError 和 ActionMessage 类. 1. ActionError – 是用来发送错误信息反馈给用户 - 通过 <s:actionerror/> 来显示. <s:if test="hasActionErrors()"> <div class="errors"> <s:actionerror/> </div> </s:if> 2. Actio

使用Data Annotations进行手动数据验证

Data Annotations是在Asp.Net中用于表单验证的 它通过Attribute直接标记字段的有效性,简单且直观.在非Asp.Net程序中(如控制台程序),我们也可以使用Data Annotations进行手动数据验证的,一个简单的例子如下(需要添加System.ComponentModel.DataAnnotations.dll的引用): using System; using System.Collections.Generic; using System.Linq; using

WPF--TextBox的验证

WPF--TextBox的验证 WPF中TextBox的自动验证: 演示 : 用以下两个TextBox分别显示验证IP和非空值验证,先看效果: IP自动验证效果: 非空值自动验证效果: 第一步:定义TextBox验证的样式:   第二步:绑定上面的样式: <TextBox x:Name="TxDataBaseIP" Style="{DynamicResource ValidationTextBoxStyle}" ..... <TextBox x:Name

优秀的PHP开源项目集合

包管理Package Management Libraries for package and dependency management. Composer/Packagist– A package and dependency manager. Composer Installers– A multi framework Composer library installer. Package Management Related Libraries related to package ma