WPF and Silverlight 学习笔记(二十二):使用代码实现绑定、绑定数据的验证

WPF and Silverlight 学习笔记(二十二):使用代码实现绑定、绑定数据的验证,第1张

概述 http://www.cnblogs.com/DragonInSea/archive/2009/05/22/1486801.html    http://www.cnblogs.com/mycom/archive/2010/12/21/1911827.html( I过T) WPF and Silverlight 学习笔记(二十二):使用代码实现绑定、绑定数据的验证 一、通过代码实现数据绑定 通过

 http://www.cnblogs.com/DragonInSea/archive/2009/05/22/1486801.html

 

 http://www.cnblogs.com/mycom/archive/2010/12/21/1911827.html( I过T)

WPF and Silverlight 学习笔记(二十二):使用代码实现绑定、绑定数据的验证 一、通过代码实现数据绑定

通过代码实现数据绑定,使用的是System.windows.Data命名空间的Binding类,主要使用Binding类的如下的属性:

Source属性:绑定到的数据源 Mode属性:绑定的模式(OneTime、OneWay、TwoWay、OneWayToSource或Default) Path属性:绑定到的数据源的属性 Converter属性:绑定时所使用的类型转换器

在绑定目标控件上使用SetBinding方法添加数据绑定。例如将MyData的name属性绑定到txtname控件的Text属性上,使用MycolorConverter转换器将MyBindingcolor的colorObject属性绑定到rec控件的Fill属性上:

   1: MyData data = new MyData();
   2:  
   3: Binding binding1 = new Binding();
   4: binding1.source = data;
   5: binding1.Mode = BindingMode.OneWay;
   6: binding1.Path = new PropertyPath("name");
   7:  
   8: txtname.SetBinding(TextBox.TextProperty,binding1);
   9:  
  10:  
  11: MyBindingcolor color = new MyBindingcolor();
  12:  
  13: Binding binding2 = new Binding();
  14: binding2.source = color;
  15: binding2.Mode = BindingMode.OneWay;
  16: binding2.Path = new PropertyPath("colorObject");
  17: binding2.Converter = new MycolorConverter();
  18:  
  19: rec.SetBinding(Rectangle.FillProperty,binding2);
二、实现绑定数据的验证:

对于绑定数据的验证,系统采用如下的机制:

使用 WPF 数据绑定模型可以将 ValIDationRules 与 Binding 对象相关联。当绑定目标的属性向绑定源属性传递属性值时(仅限TwoWay模式或OneWayToSource模式),执行ValIDationRule中的ValIDate方法,实现对界面输入数据的验证。

定义验证可以采用以下三种:

DataErrorValIDationRule:检查由源对象的 IDataErrorInfo 实现所引发的错误,要求数据源对象实现System.ComponentModel命名空间的IDataErrorInfo接口。

例如,定义一个学生信息类,要求其学生成绩在0到100间,学生姓名的长度在2到10个字符间:

1: public class StudentInfoWithValIDation : IDataErrorInfo
   2: {
   3:     #region 构造方法
   4:     public StudentInfoWithValIDation()
   5:     {
   6:         Studentname = "Tom";
   7:         score = 90;
   8:     }
   9:     public StudentInfoWithValIDation(string m_Studentname,double m_score)
  10:     {
  11:         Studentname = m_Studentname;
  12:         score = m_score;
  13:     }
  14:     #endregion
  15:  
  16:     #region 属性
  17:     public string Studentname
  18:     {
  19:         get; set;
  20:     }
  21:     public double score
  22:     {
  23:         get; set;
  24:     }
  25:     #endregion
  26:  
  27:     #region 实现IDataErrorInfo接口的成员
  28:     public string Error
  29:     {
  30:         get 
  31:         {
  32:             return null;
  33:         }
  34:     }
  35:  
  36:     public string this[string columnname]
  37:     {
  38:         get
  39:         {
  40:             string result = null;
  41:  
  42:             switch (columnname)
  43:             {
  44:                 case "Studentname":
  45:                     // 设置Studentname属性的验证规则
  46:                     int len = Studentname.Length;
  47:                     if (len < 2 || len > 10)
  48:                     {
  49:                         result = "Studentname length must between 2 and 10";
  50:                     }
  51:                     break;
  52:                 case "score":
  53:                     // 设置score属性的验证规则
  54:                     if (score < 0 || score > 100)
  55:                     {
  56:                         result = "score must between 0 and 100";
  57:                     }
  58:                     break;
  59:             }
  60:  
  61:             return result;
  62:         }
  63:     }
  64:     #endregion
  65: }

在界面上,定义两个TextBox绑定到Studentname和score两个属性上,并设置其采用DataErrorValIDationRule:

1: <Window x:Class="WPFDataBindingDemo.WinDataErrorValIDationRuleDemo"
   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:     xmlns:local="clr-namespace:WPFDataBindingDemo"
   5:     Title="WinDataErrorValIDationRuleDemo" Height="154" WIDth="300">
   6:     <Canvas Height="116" x:name="mainCanvas">
   7:         <Canvas.Resources>
   8:             <local:StudentInfoWithValIDation x:Key="myData" />
   9:         </Canvas.Resources>
  10:         <Canvas.DataContext>
  11:             <Binding Source="{StaticResource myData}" />
  12:         </Canvas.DataContext>
  13:         <Label Canvas.left="10" Canvas.top="10" Height="28" name="label1" WIDth="120">Studentname:</Label>
  14:         <Label Canvas.left="10" Canvas.top="36" Height="28" name="label2" WIDth="120">score:</Label>
  15:         <TextBox Canvas.left="136" Canvas.top="12" Height="23" name="textBox1" WIDth="120">
  16:             <TextBox.Text>
  17:                 <Binding Path="Studentname" 
  18:                          Mode="TwoWay" 
  19:                          UpdateSourceTrigger="PropertyChanged"
  20:                          ValIDatesOnDataErrors="True" />
  21:             </TextBox.Text>
  22:         </TextBox>
  23:         <TextBox Canvas.left="136" Canvas.top="41" Height="23" name="textBox2" WIDth="120">
  24:             <TextBox.Text>
  25:                 <Binding Path="score" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
  26:                     <!--与上一个TextBox控件的写法作用相同-->
  27:                     <Binding.ValIDationRules>
  28:                         <DataErrorValIDationRule />
  29:                     </Binding.ValIDationRules>
  30:                 </Binding>
  31:             </TextBox.Text>
  32:         </TextBox>
  33:         <button Canvas.left="12" Canvas.top="79" Height="23" name="button1" WIDth="118" Click="button1_Click">Get Student Info</button>
  34:         <button Canvas.left="136" Canvas.top="79" Height="23" name="button2" WIDth="118" Click="button2_Click">Get ValIDate State</button>
  35:     </Canvas>
  36: </Window>

从执行的结果上来看,当验证出现错误(即索引器属性返回的字符串不为空时),系统默认给出一种验证错误的显示方式(控件以红色边框包围),但是需注意两点:

产生验证错误,验证后的数据仍然会更改数据源的值 如果系统出现异常,如成绩值输入 “90d”,则系统不会显示错误,控件上的输入值也不赋值到数据源。这种情况下,需要使用ExceptionValIDationRule。 ExceptionValIDationRule:即当绑定目标的属性值向绑定源的属性值赋值时引发异常所产生的验证。此种方式若实现自定义的逻辑验证,通常设置数据源的属性的Set访问器,在Set访问器中,根据输入的值结合逻辑,使用throw抛出相应的异常。

例如上例中,对于score对应的TextBox,再加入ExceptionValIDationRule:

1: <TextBox Canvas.left="136" Canvas.top="41" Height="23" name="textBox2" WIDth="120">
   2:     <TextBox.Text>
   3:         <Binding Path="score" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
   4:             <!--与上一个TextBox控件的写法作用相同-->
   5:             <Binding.ValIDationRules>
   6:                 <DataErrorValIDationRule />
   7:                 <ExceptionValIDationRule />
   8:             </Binding.ValIDationRules>
   9:         </Binding>
  10:     </TextBox.Text>
  11: </TextBox>

自定义验证规则:定义一个类,继承ValIDationRule抽象类,实现其ValIDate方法,验证某一输入。

例如,定义一个类,用来验证输入的Email地址是否合法(验证的Email允许为字符串的空值String.Empty,但有输入必须符合Email的格式要求)

在学生类中添加Email可读可写属性(并不做相应的验证,忽略其他重复代码):

1: public string Email
   3:     set; get;
   4: }

定义一个类,实现Email格式验证:

1: using System.Globalization;
   2: using System.Text.RegularExpressions;
   3: using System.windows.Controls;
   4:  
   5: namespace WPFDataBindingDemo
   6: {
   7:     public class EmailValIDationRule : ValIDationRule
   8:     {
   9:         public overrIDe ValIDationResult ValIDate(object value,CultureInfo cultureInfo)
  10:         {
  11:             bool isValID = false;
  12:             string message = null;
  13:  
  14:             // 检查输入值不为空,且是字符串
  15:             if (value != null && value is string)
  16:             {
  17:                 string email = value.ToString();
  19:                 // 检查输入的字符串是否为String.Empty
  20:                 if (email != string.Empty)
  21:                 {
  22:                     string emailFormartRegex =
  23:                         @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.)|" +
  24:                         @"(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
  25:                     
  26:                     // 检查输入的字符串是否符合Email格式
  27:                     isValID = Regex.IsMatch(email,emailFormartRegex);
  28:  
  29:                     if (! isValID)
  30:                     {
  31:                         message = "input string not match Email Format";
  32:                     }
  33:                 }
  34:                 else
  35:                 {
  36:                     // 输入的字符串为字符串空值时,认为验证通过
  37:                     isValID = true;
  38:                 }
  39:             }
  40:             else
  41:             {
  42:                 message = "input value is NulL or is not string.";
  43:             }
  44:  
  45:             // 返回验证结果(ValIDationResult对象)
  46:             return new ValIDationResult(isValID,message);
  47:         }
  48:     }
  49: }

在界面上:

1: <TextBox Canvas.left="104" Canvas.top="70" Height="23" name="textBox3" WIDth="152">
   2:     <Binding Mode="TwoWay" Path="Email" UpdateSourceTrigger="PropertyChanged">
   3:         <Binding.ValIDationRules>
   4:             <local:EmailValIDationRule />
   5:         </Binding.ValIDationRules>
   6:     </Binding>
   7: </TextBox>

三、为数据验证提供视觉效果

在数据验证错误后,可以通过以下两种方式提供相应的视觉效果:

定义Style及相应的触发器

如果要使输入的控件的外观发生变化,可以使用Style。例如上例中出错,使输入的文本框的背景颜色和字体颜色发生变化,并提供tooltip显示错误信息,可以定义如下的Style:

1: <Style targettype="TextBox">
   2:     <Setter Property="Background" Value="White" />
   3:     <Setter Property="Foreground" Value="Black" />
   4:     <Style.Triggers>
   5:         <Trigger Property="ValIDation.HasError" Value="True">
   6:             <Setter Property="Background" Value="#DDD" />
   7:             <Setter Property="Foreground" Value="Red" />
   8:             <Setter Property="tooltip"
   9:                     Value="{Binding relativeSource={relativeSource Self},Path=(ValIDation.Errors)[0].ErrorContent}"/>
  10:         </Trigger>
  11:     </Style.Triggers>
  12: </Style>

效果如下:

 

定义控件模板

如果要为相应的控件添加一些辅助的控件,可以使用控件模板,如出现验证错误时,不使用系统默认的红色边框,而是在文本框后添加一个红色的星号:

1: <ControlTemplate x:Key="valIDErrorTextBoxTemplate">
   2:     <DockPanel>
   3:         <AdornedElementPlaceholder/>
   4:         <TextBlock Foreground="Red" FontSize="20">*</TextBlock>
   5:     </DockPanel>
   6: </ControlTemplate>

并在每一个输入的TextBox中添加:

1: ValIDation.ErrorTemplate="{StaticResource valIDErrorTextBoxTemplate}"

 

本系列博客索引页 总结

以上是内存溢出为你收集整理的WPF and Silverlight 学习笔记(二十二):使用代码实现绑定、绑定数据的验证全部内容,希望文章能够帮你解决WPF and Silverlight 学习笔记(二十二):使用代码实现绑定、绑定数据的验证所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1071102.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存