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
ControlTemplate
withAdornedElementPlaceHolder
- 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.
<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:
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.
<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:
<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: ...
随机推荐
- js实现换肤效果
一,js换肤的基本原理 基本原理很简单,就是使用 JS 切换对应的 CSS 样式表文件.例如导航网站 Hao123 的右上方就有网页换肤功能.除了切换 CSS 样式表文件之外,通常的网页换肤还需要通过 ...
- Django1.10主题指南—模型
模型是你的数据的唯一的.权威的信息源.它包含你所储存数据的必要字段和操作行为.通常,每个模型都对应着数据库中的唯一一张表. 基础认识: 每个model都是一个继承 django.db.models.M ...
- js正则知识点
正则主要是用来匹配有规律的字符串,也就是说你要写一个正则前你必须非常清楚该类型字符串的规则,(比如邮箱)如果你没了解邮箱的规则那么你正则无论怎么写都是错的. \w字符(字母数字下划线)\W非字符\s空 ...
- 团队作业10——项目复审与事后分析(Beta阶段)
一.Beta阶段项目复审 http://www.cnblogs.com/womenshuodedoudui/p/7001208.html 二.事后诸葛分析 http://www.cnblogs.com ...
- 201521123070 《JAVA程序设计》第14周学习总结
1. 本章学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多数据库相关内容. 2. 书面作业 Q1. MySQL数据库基本操作 建立数据库,将自己的姓名.学号作为一条记录插入.(截图,需出现 ...
- Markdow使用的简单介绍
一个例子: 例子开始 1. 本章学习总结 (字体较大,用法:#你要放大的标题) 今天主要学习了三个知识点 封装 继承 多态 用法: - 封装 - 继承 - 多态 2. 书面作业 Q1. java He ...
- SpringMVC第二篇【过滤编码器、注解开发、requestMapping、业务方法与传统参数】
SpringMVC过滤编码器 在SpringMVC的控制器中,如果没有对编码进行任何的操作,那么获取到的中文数据是乱码! 即使我们在handle()方法中,使用request对象设置编码也不行!原因也 ...
- 转 Java输入输出流详解(非常详尽)
转 http://blog.csdn.net/zsw12013/article/details/6534619 通过数据流.序列化和文件系统提供系统输入和输出. Java把这些不同来源和目标的数据都 ...
- Ansible系列(三):YAML语法和playbook写法
html { font-family: sans-serif } body { margin: 0 } article,aside,details,figcaption,figure,footer,h ...
- java实现excel和数据的交互
1. 环境要求 本文环境为: 数据库为oracle,jdk为jdk7,依赖jar包为ojdbc6-11.2.0.4.0.jar+poi-3.14.jar 2.POI 使用 1. 建立工作空间 2. 获 ...