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: ...
随机推荐
- 10 Logistic Regression
线性分类中的是非题 --->概率题 (设置概率阈值后,大于等于该值的为O,小于改值的为X) --->逻辑回归 O为1,X为0 逻辑回归假设 逻辑函数/S型函数:光滑,单调 自变量趋于负无穷 ...
- Mac系统的终端显示git当前分支
当我第一次在mac系统下使用git的时候,发现一个问题,git默认是不显示当前所在的分支名称,然后网上查找资料,找到了解决办法,终于可以显示本地当前分支,现在分享如下. 1 进入你的home目录 cd ...
- PS小实验-去除水印
PS小实验-去除水印 水印是一些品牌商覆盖在图片或视频上的一个商标logo或小文本,比如大家最讨厌的百度logo,作者本人也是比较讨厌水印的,让好端端的一张图片变得美中不足. 个人觉得用photosh ...
- 201521123118《java程序设计》第一周学习总结
1. 本周学习总结 根据学习的过程中,虽然听学习过的人说过,c语言和java语言差不多,学习过c语言 在学java会比较容易,但是这一周发现,java和c还是有一些差别的: java语言是面向对象的语 ...
- ASCII中关于大小写字母间隔为32的思考
一直没有搞清楚为什么在ASCII中要把大小写字母的间隔设置为32,今天才发现这样设置的精妙之处:方便了程序对大小写字母进行转换.请看: ================= 十进制 32 ...
- 201521123090《Java程序设计》第12周学习总结
本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多流与文件相关内容. 书面作业 将Student对象(属性:int id, String name,int age,double grad ...
- java基础知识6-- 抽象类,抽象方法,接口,构造方法,类方法等易混淆的知识点
一.抽象类和抽象方法 (B 继承 抽象类A) 抽象类:有抽象方法的一定是抽象类 抽象方法:方法名前有abstract修饰,且方法没有方法体,即{},不需要实现任何功能,只是声明 1.抽象类中的方法有 ...
- Ubuntu Server 12.04安装图解教程
Ubuntu S ...
- [js高手之路] 设计模式系列课程 - 迭代器(1)
迭代器是指通过一种形式依次遍历数组,对象,或者类数组结构中的每个元素. 常见的有jquery中的each方法, ES5自带的forEach方法. 下面我们就来自定义一个类似jquery或者ES5的迭代 ...
- MySQL基本语法(一):和SQL Server语法的差异小归纳
html { font-family: sans-serif } body { margin: 0 } article,aside,details,figcaption,figure,footer,h ...