Simple Validation 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:
- Create a
ControlTemplatewithAdornedElementPlaceHolder - 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 Codepublic 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.
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 bin ...
- [WPF系列]-Data Validation
项目经常前台界面涉及到用户输入时,我们常常会用到数据有效性的验证.在网页中我们之前用js来校验Form中的数据有效性.在WPF中我们如何实现这种验证机制了?答案:INotifyDataErrorInf ...
- WPF 验证没有通过无法保存数据(非常好)+ 虚似数据库
Validation control with a single validation rule is easy, but what if we need to validate a control ...
- [WPF系列]-Prism+EF
源码:Prism5_Tutorial 参考文档 Data Validation in WPF √ WPF 4.5 – ASYNCHRONOUS VALIDATION Reusable asyn ...
- WPF 验证
WPF中TextBox的自动验证: 演示 : 用以下两个TextBox分别显示验证IP和非空值验证,先看效果: IP自动验证效果: 非空值自动验证效果: 第一步:定义TextBox验证的样式: < ...
- WPF 自动验证
WPF中TextBox的自动验证: 演示 : 用以下两个TextBox分别显示验证IP和非空值验证,先看效果: IP自动验证效果: 非空值自动验证效果: 第一步:定义TextBox验证的样式: < ...
- 为WIN8 APP创建置顶desktop应用
Windows 8: TopMost window I am working on my next ambitious project “MouseTouch” which is multi to ...
- MVVM中数据验证之 ViewModel vs. Model
MMVM模式示意图. View绑定到ViewModel,然后执行一些命令在向它请求一个动作.而反过来 ...
- nuget packages batch install
d:\nuget\nuget.exe install EnterpriseLibrary.Common -NoCache -Verbosity detailed -OutputDirectory D: ...
随机推荐
- JavaScript学习日志(二):面向对象的程序设计
1,ECMAScript不像其他面向对象的语言那样有类的概念,它的对象与其他不同. 2,ECMAScript有两种属性:数据属性和访问器属性.([[]]这种双中括号表示属性为内部属性,外部不可直接访问 ...
- 团队作业4--第一次项目冲刺(Alpha版本)6
一.Daily Scrum Meeting照片 二.燃尽图 三.项目进展 1.对功能界面进行优化 2.对算法进行改进优化,提高运行速度 四.困难与问题 首先我们团队通过讨论,对功能界面进行了优化,让界 ...
- 扫雷游戏制作过程(C#描述):第四节、菜单操作
前言 这里给出教程原文地址. 该项目已经放在github上托管. 菜单操作 我们现在的程序单击菜单的时候不会有任何反应,这一节我们主要介绍菜单的相关代码,使得菜单能够正常使用. 现在我们希望在对应级别 ...
- 201521123036 《Java程序设计》第6周学习总结
本周学习总结 1.1 面向对象学习暂告一段落,请使用思维导图,以封装.继承.多态为核心概念画一张思维导图,对面向对象思想进行一个总结. 1.2 可选:使用常规方法总结其他上课内容. 对象克隆:Clon ...
- 201521123104 《Java程序设计》第6周学习总结
1. 本周学习总结 1.1 面向对象学习暂告一段落,请使用思维导图,以封装.继承.多态为核心概念画一张思维导图,对面向对象思想进行一个总结. 2. 书面作业 1. clone方法 1.1 Object ...
- 201521123028 《Java程序设计》第2周学习总结
1. 本周学习总结 1.学习了String及部分函数用法,例如PTA上<5-2 jmu-Java-02基本语法-02-StringBuilder>一题中用到了"str.appen ...
- 201521123054《Java程序设计》第1周学习总结
#1. 本章学习总结 你对于本章知识的学习总结 本章我们学习了各种java相关文件的使用,能够进行基本的程序操作: 学会使用博客.码云与PTA管理java: #2. 书面作业 1.为什么java程序可 ...
- 201521123106 《Java程序设计》第12周学习总结
1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多流与文件相关内容. 2. 书面作业 将Student对象(属性:int id, String name,int age,doubl ...
- Python学习笔记013_正则表达式
Python中的正则表达式是通过 re 模块实现的. 通配符 . 表示除了换行以外的任何字符; 编写正则表达式时使用 r're' , r + 正则表达式内容 >>> impor ...
- grunt学习笔记1 理论知识
你需要检查js语法错误,然后再去压缩js代码.如果这两步你都去手动操作,会耗费很多成本.Grunt就能让你省去这些手动操作的成本. “—save-dev”的意思是,在当前目录安装grunt的同时,顺便 ...