惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
Forbes - Security
Forbes - Security
WordPress大学
WordPress大学
P
Proofpoint News Feed
T
Threat Research - Cisco Blogs
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
Spread Privacy
Spread Privacy
D
Darknet – Hacking Tools, Hacker News & Cyber Security
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
P
Privacy International News Feed
A
About on SuperTechFans
T
Tailwind CSS Blog
I
InfoQ
S
Securelist
云风的 BLOG
云风的 BLOG
罗磊的独立博客
Recent Announcements
Recent Announcements
T
The Exploit Database - CXSecurity.com
B
Blog RSS Feed
V
Visual Studio Blog
Know Your Adversary
Know Your Adversary
The GitHub Blog
The GitHub Blog
Jina AI
Jina AI
腾讯CDC
Cyberwarzone
Cyberwarzone
有赞技术团队
有赞技术团队
AWS News Blog
AWS News Blog
博客园 - 【当耐特】
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
F
Full Disclosure
S
Secure Thoughts
博客园 - 司徒正美
J
Java Code Geeks
Y
Y Combinator Blog
Google Online Security Blog
Google Online Security Blog
GbyAI
GbyAI
N
News and Events Feed by Topic
Help Net Security
Help Net Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Project Zero
Project Zero
T
Tenable Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tor Project blog
MyScale Blog
MyScale Blog
Scott Helme
Scott Helme
小众软件
小众软件
K
Kaspersky official blog

博客园 - Haozes

新Blog 拼写检查算法 Golang 版 Windbg 离线调试.Net 程序入门 (译)你必须知道的位运算技巧 Low Level Bit Hacks You Absolutely Must Know Windows 下 命令行增强工具 WPF Layout & Image异步加载 几篇文章了解编译原理 WPF 实现Loading效果 推荐一个.NET 命令行参数Parser 库 常用开发工具介绍 使用.Net Memory Profiler 分析.Net程序内存泄露 使用Mdbg.exe 调试.Net 程序 WPF 多语言方案 .Net 2 Tip :捕获CSE和Thread.Timer与Thread.Sleep比较 使用CSharp Driver操作Mongodb介绍 使用Python操作MSSQL数据库. 运行.Net4.0程序是否要安装之前的.Net版本 javascript Disable <div> or other tag in Other Browser like FF,Chrome Delphi 无类型参数传递动态数组和静态数组
WPF Binding Validation 数据验证
Haozes · 2012-07-02 · via 博客园 - Haozes

表单的数据验证往往枯燥无味,又不可避免.
在一个如下表单只有两个输入框,和确定按钮的情况下,正常我们需要做哪些工作呢?
validation

1. 如果年龄输入框输入了非数字的字符串,输入框失去焦点后,后面错误消息应当能立即提示出来

2.错误的提示的内容如果变化,你可能需要修改整个UI设计.(如显示在输入框下方)

3.点击OK按钮,需要遍历Window所有输入框,如果有输入数据验证不符合,需要提示错误,并将对应的控件获取焦点.

这很容易么?当这个输入框再多一些呢?

下面的Demo,看在WPF如何轻松处理这些:

validation2

Window里,textBox1,textBox2,textBox3 绑定的数据为:

DataSource
  • 使用自定义验证规则
<TextBox Name="textBox1" Width="50" FontSize="15"
         Validation.ErrorTemplate="{StaticResource validationTemplate}"
         Style="{StaticResource textBoxInError}"
         Grid.Row="1" Grid.Column="1" Margin="2">
  <TextBox.Text>
    <Binding Path="Age" Source="{StaticResource ods}"
             UpdateSourceTrigger="PropertyChanged" >
      <Binding.ValidationRules>
        <c:AgeRangeRule Min="21" Max="130"/>
      </Binding.ValidationRules>
    </Binding>
  </TextBox.Text>
</TextBox>

textBox1 绑定了Age ,并且使用的验证的规则为 AgeRangeRule ,规则中指定了最小值和最大值,当PropertyChanged时验证规则将触发,也就是该控件失去焦点之时. 提示的信息样式定义在ErrorTemplate里,让我们再来看一看ErrroTemplate的内容:

      <ControlTemplate x:Key="validationTemplate">
        <DockPanel>
          <TextBlock Foreground="Red" FontSize="20">!</TextBlock>
          <AdornedElementPlaceholder/>
        </DockPanel>
      </ControlTemplate>


AdornedElementPlaceholder 才是这里的点睛之处,此处放置了待验证的控件,而整个ErrorTemplate正是使用神奇的Adoner实现了错误的提示的位置和原排版布局的无关性. 验证规则和整个代码完全解耦:

rule
     <Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
        <Style.Triggers>
          <Trigger Property="Validation.HasError" Value="true">
            <Setter Property="ToolTip"
              Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                              Path=(Validation.Errors)[0].ErrorContent}"/>
          </Trigger>
        </Style.Triggers>
      </Style>
  • 使用ExceptionValidationRule


另一种方法,不自定义Rule,如:

 <TextBox Name="textBox3" Width="50" FontSize="15"
             Grid.Row="5" Grid.Column="1" Margin="2"
             Validation.ErrorTemplate="{StaticResource validationTemplate}"
             Style="{StaticResource textBoxInError}">
      <TextBox.Text>
        <Binding Path="Age3" Source="{StaticResource ods}"
                 UpdateSourceTrigger="PropertyChanged">
          <Binding.ValidationRules>
            <ExceptionValidationRule/>
          </Binding.ValidationRules>
        </Binding>
      </TextBox.Text>
    </TextBox>

在后台代码中:

 
        BindingExpression myBindingExpression = textBox3.GetBindingExpression(TextBox.TextProperty);
            Binding myBinding = myBindingExpression.ParentBinding;
            myBinding.UpdateSourceExceptionFilter = new UpdateSourceExceptionFilterCallback(ReturnExceptionHandler);
            myBindingExpression.UpdateSource();

因为Age3Int类型,在textBox3 输入非int类型,将会引发异常,此时使用Rule的正是系统的ExceptionValidationRule,同样错误信息的模块不变.

  • 验证所有控件

    
    

    在点击确定可使用该方法再次验证,在数据不合法的情况下,使用户无法提交

代码: 下载