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. RAID基础知识总结

    1.RAID RAID:Redundant Arrays of Inexpensive(Independent)Disks,即独立磁盘冗余阵列,简称磁盘阵列.简单地说就是把多个独立的硬盘组合起来,从而 ...

  2. 团队作业8——Beta 阶段冲刺6th day

    一.当天站立式会议 二.每个人的工作 (1)昨天已完成的工作(具体在表格中) 完善订单功能 (2)今天计划完成的工作(具体如下) 完善支付功能 (3) 工作中遇到的困难(在表格中) 成员 昨天已完成的 ...

  3. 201521123004 《Java程序设计》第10周学习总结

    1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结异常与多线程相关内容. 答: 异常的概念上周的思维导图大致体现,这周就归纳一下错误调试 由于多线程的内容比较散,我就直接用文字总结 ...

  4. Smrty模版总结(转)

    转自:http://www.cppblog.com/amazon/archive/2011/11/21/160638.html 前提:1. 部署smarty模板目录:2. 编写Smarty类的子类,定 ...

  5. Ansible系列(二):选项和常用模块

    html { font-family: sans-serif } body { margin: 0 } article,aside,details,figcaption,figure,footer,h ...

  6. WPF(C#) 矩阵拖动、矩阵动画、边缘展开动画处理。

    最近在研发新的项目,遇到了一个桌面模式下的难点--展开动画.之前动画这方面没做过,也许很多人开始做的时候也会遇到相关问题,因此我把几个重点及实际效果图总结展示出来: 我的开发环境是在VS2017下进行 ...

  7. Hibernate中fetch和lazy介绍

    fetch ,指定关联对象抓取的方式,可以设置fetch = "select" 和 fetch = "join".select方式时先查询返回要查询的主体对象( ...

  8. 浅谈大数据和hadoop家族

    按照时间的早晚从大数据出现之前的时代讲到现在.暂时按一个城市来比喻吧,反正Landscape的意思也大概是”风景“的意思. 早在大数据概念出现以前就存在了各种各样的关于数学.统计学.算法.编程语言的研 ...

  9. 初入ubuntu

    登入root :su root 安装 vim: sudo apt-get install vim 安装 gcc(g++):sudo apt-get install gcc(g++) 非常实用的修改分辨 ...

  10. EGit使用教程:第一篇 添加工程到版本控制

    配置 确定身份 当每次提交的时候,Git需要跟踪这次提交,确认是哪个用户提交的.用户由 user.name 和 user.email 组成,这个信息包含在 ~/.gitconfig 文件中. ~ 代表 ...