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.

Simple Validation in WPF的更多相关文章

  1. 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 ...

  2. [WPF系列]-Data Validation

    项目经常前台界面涉及到用户输入时,我们常常会用到数据有效性的验证.在网页中我们之前用js来校验Form中的数据有效性.在WPF中我们如何实现这种验证机制了?答案:INotifyDataErrorInf ...

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

    Validation control with a single validation rule is easy, but what if we need to validate a control ...

  4. [WPF系列]-Prism+EF

      源码:Prism5_Tutorial   参考文档 Data Validation in WPF √ WPF 4.5 – ASYNCHRONOUS VALIDATION Reusable asyn ...

  5. WPF 验证

    WPF中TextBox的自动验证: 演示 : 用以下两个TextBox分别显示验证IP和非空值验证,先看效果: IP自动验证效果: 非空值自动验证效果: 第一步:定义TextBox验证的样式: < ...

  6. WPF 自动验证

    WPF中TextBox的自动验证: 演示 : 用以下两个TextBox分别显示验证IP和非空值验证,先看效果: IP自动验证效果: 非空值自动验证效果: 第一步:定义TextBox验证的样式: < ...

  7. 为WIN8 APP创建置顶desktop应用

    Windows 8: TopMost window   I am working on my next ambitious project “MouseTouch” which is multi to ...

  8. MVVM中数据验证之 ViewModel vs. Model

                                                      MMVM模式示意图. View绑定到ViewModel,然后执行一些命令在向它请求一个动作.而反过来 ...

  9. nuget packages batch install

    d:\nuget\nuget.exe install EnterpriseLibrary.Common -NoCache -Verbosity detailed -OutputDirectory D: ...

随机推荐

  1. Web云笔记--CSS

    CSS CSS CSS Web自学第二阶段之CSS 参考资料:<Head First HTML&CSS>(中文第二版)(美国)弗里昂ISBN:9787508356464 中国电力出 ...

  2. 转:【深入Java虚拟机】之六:Java语法糖

    转载请注明出处:http://blog.csdn.net/ns_code/article/details/18011009 语法糖(Syntactic Sugar),也称糖衣语法,是由英国计算机学家P ...

  3. 201521123114 《Java程序设计》第2周学习总结

    #1. 本周学习总结 1. 学会了使用码云管理代码,使用eclipse关联jdk源代码: 2. 学习了包管理机制,包的作用:主要是管理java文件,解决同名文件冲突; 3. ArrayList可以处理 ...

  4. 201521123080《Java程序设计》第13周学习总结

    1. 本周学习总结 以你喜欢的方式(思维导图.OneNote或其他)归纳总结多网络相关内容. 1.网络编程概述 (1)网络模型 OSI参考模型 TCP/IP参考模型 (2)网络通讯要素 IP地址 端口 ...

  5. 201521123110《Java程序设计》第12周学习总结

    1. 本周学习总结 2. 书面作业 1. 字符流与文本文件:使用 PrintWriter(写),BufferedReader(读) 1.1 生成的三个学生对象,使用PrintWriter的printl ...

  6. 201521123085 《Java程序设计》第14周学习总结

    1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多数据库相关内容. 2. 书面作业 1. MySQL数据库基本操作 建立数据库,将自己的姓名.学号作为一条记录插入.(截图,需出现自 ...

  7. Markdown 模板

    一个例子: 例子开始 1. 本章学习总结 今天主要学习了三个知识点 封装 继承 多态 2. 书面作业 Q1. java HelloWorld命令中,HelloWorld这个参数是什么含义? 今天学了一 ...

  8. Spring第二篇和第三篇的补充【JavaConfig配置、c名称空间、装载集合、JavaConfig与XML组合】

    前言 在写完Spring第二和第三篇后,去读了Spring In Action这本书-发现有知识点要补充,知识点跨越了第二和第三篇,因此专门再开一篇博文来写- 通过java代码配置bean 由于Spr ...

  9. Servlet第七篇【Cookie和Session的区别、应用】

    Session和Cookie的区别 从存储方式上比较 Cookie只能存储字符串,如果要存储非ASCII字符串还要对其编码. Session可以存储任何类型的数据,可以把Session看成是一个容器 ...

  10. js对象详解(JavaScript对象深度剖析,深度理解js对象)

    js对象详解(JavaScript对象深度剖析,深度理解js对象) 这算是酝酿很久的一篇文章了. JavaScript作为一个基于对象(没有类的概念)的语言,从入门到精通到放弃一直会被对象这个问题围绕 ...