拼吾爱程序人生

首页»  Silverlight»  SilverLight学习笔记--实际应用(一)(4):手把手建立一个Silverlight应用程序之同步数据校验1
cobra - 2009-9-11 12:27:00
上一篇:SilverLight学习笔记--实际应用(一)(3):手把手建立一个Silverlight应用程序之删除记录

现在我们的程序有了添加和删除以及修改功能,下面我们看一看如何让程序具备数据校验功能。我们将用两种方式实现数据的校验,一种是在客户端进行同步校验。另一种是在服务器端进行异步校验。

  本篇我们先实现如何在客户端进行同步校验。基本原理是:利用数据的双向绑定和INotifyPropertyChanged 接口以及控件的NotifyOnValidationError与ValidatesOnExceptions两个属性设置来配合实现客户端同步校验。

现在继续修改完善我们的程序。

1、修改用户界面如下:
  1. <UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  x:Class="SLApplicationDataTest.Page"
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.     Width="400" Height="300">
  5.     <StackPanel Height="500" Background="White">
  6.         <StackPanel Orientation="Horizontal">
  7.             <Button x:Name="addButton" Content="Add" Margin="10"/>
  8.             <Button x:Name="deleteButton" Content="Delete" Margin="10"/>
  9.         </StackPanel>
  10.         <data:DataGrid x:Name="dgPeople" AutoGenerateColumns="False" >
  11.             <data:DataGrid.Columns>
  12.                 <data:DataGridTextColumn    Header="Name"  Binding="{Binding Name}"  />
  13.                 <data:DataGridTextColumn    Header="Sex"  Binding="{Binding Sex}"  />
  14.                 <data:DataGridTemplateColumn Header="Age">
  15.                     <data:DataGridTemplateColumn.CellTemplate >
  16.                         <DataTemplate>
  17.                             <TextBlock  Text="{Binding Age}"  ToolTipService.ToolTip="请输入0至200之间的整数!"></TextBlock>
  18.                         </DataTemplate>
  19.                     </data:DataGridTemplateColumn.CellTemplate>
  20.                     <data:DataGridTemplateColumn.CellEditingTemplate>
  21.                         <DataTemplate>
  22.                             <TextBox Text="{Binding Age , Mode=TwoWay, NotifyOnValidationError=True,  ValidatesOnExceptions=True}" BindingValidationError="TextBox_BindingValidationError"
  23.                                     ToolTipService.ToolTip="请输入0至200之间的整数!"></TextBox>
  24.                         </DataTemplate>
  25.                     </data:DataGridTemplateColumn.CellEditingTemplate>
  26.                 </data:DataGridTemplateColumn>
  27.                 <data:DataGridTextColumn    Header="Address"  Binding="{Binding Address}"  />
  28.             </data:DataGrid.Columns>
  29.         </data:DataGrid>
  30.     </StackPanel>
  31. </UserControl>
复制代码
在此界面中,我们不再是简单地进行绑定数据和显示数据,而是对DataGrid控件进行了改造,尤其是运用了模板来定义我们的Age字段。注意Age字段的CellEditingTemplate模板,它的两个属性:NotifyOnValidationError,ValidatesOnExceptions都必须设置为true,这样才会在绑定出错时报错,而对错误事件的处理则字义在BindingValidationError事件中。
Silverlight栏目的最新浏览文章:
• 通过动态构造实体在Silverlight 中给DataGrid 绑定数据
• Silverlight基于WCF双工以及.NET TCP协议即时通讯系统
• Silverlight 4 离线简体中文版帮助文档
• 使用Silverlight构建一个工作流设计器(十六)-持久化数据到数据库—数据库结构
• 最新Microsoft Expression Studio 3破解
• 微软Expression Blend 3中文教程
• 【Silverlight】利用IsolatedStorageFile实现客户端缓存
• Silverlight 的弹出窗体--展示
• Silverlight 4中使用MEF实现页面的动态装配
• Silverlight实现360度全景展示效果
• Pro Business Applications with Silverlight 4
• Silverlight实时3D渲染引擎:SilverMotion
• Silverlight中把WriteableBitmap转为Byte流并保存到本地
• Silverlight 图片局部放大效果
• Silverlight 4 User Interface Cookbook
• Silverlight 相册DEMO--ImageSnipper(V2)
cobra - 2009-9-11 12:27:00
2、修改Person类

在此类中加入绑定数据的校验工作。具体代码如下:
  1. Public int Age
  2.         {
  3.             get { return _age; }
  4.             set
  5.             {
  6.                 if (value == _age) return;

  7.                 //如果输入的不是整数,则抛出异常
  8.                 try
  9.                 {
  10.                     Convert.ToInt32(value);
  11.                 }
  12.                 catch(Exception ex)
  13.                 {
  14.                     throw new Exception(ex.ToString());
  15.                 }
  16.                
  17.                 //如果输入的整数不在合理范围同,则也抛出异常

  18.                 if (value < 0 || value > 200)
  19.                 {
  20.                     throw new Exception("Age must be between 0 and 200");
  21.                 }


  22.                 _age = value;
  23.                 OnPropertyChanged("Age");
  24.             }
  25.         }
复制代码
Person类全部代码如下:
  1. using System;
  2. using System.Net;
  3. using System.Windows;
  4. using System.Windows.Controls;
  5. using System.Windows.Documents;
  6. using System.Windows.Ink;
  7. using System.Windows.Input;
  8. using System.Windows.Media;
  9. using System.Windows.Media.Animation;
  10. using System.Windows.Shapes;
  11. using System.ComponentModel; //因为要用到INotifyPropertyChanged接口


  12. namespace SLApplicationDataTest
  13. {
  14.     public class Person : INotifyPropertyChanged
  15.     {
  16.         private string _name;
  17.         private string _sex;
  18.         private int _age;
  19.         private string _address;

  20.         #region Constructors
  21.         public Person() { }

  22.         public Person(string NameStr, string SexStr, int AgeInt, string AddressStr)
  23.         {
  24.             this._name = NameStr;
  25.             this._sex = SexStr;
  26.             this._age = AgeInt;
  27.             this._address = AddressStr;
  28.         }
  29.         #endregion


  30.         #region Properties

  31.         public string Name
  32.         {
  33.             get { return _name; }
  34.             set
  35.             {
  36.                 if (value == _name) return;
  37.                 _name = value;
  38.                 OnPropertyChanged("Name");
  39.             }
  40.         }

  41.         public string Sex
  42.         {
  43.             get { return _sex; }
  44.             set
  45.             {
  46.                 if (value == _sex) return;
  47.                 _sex = value;
  48.                 OnPropertyChanged("Sex");
  49.             }
  50.         }

  51.         public int Age
  52.         {
  53.             get { return _age; }
  54.             set
  55.             {
  56.                 if (value == _age) return;

  57.                 //如果输入的不是整数,则抛出异常
  58.                 try
  59.                 {
  60.                     Convert.ToInt32(value);
  61.                 }
  62.                 catch(Exception ex)
  63.                 {
  64.                     throw new Exception(ex.ToString());
  65.                 }
  66.                
  67.                 //如果输入的整数不在合理范围同,则也抛出异常

  68.                 if (value < 0 || value > 200)
  69.                 {
  70.                     throw new Exception("Age must be between 0 and 200");
  71.                 }


  72.                 _age = value;
  73.                 OnPropertyChanged("Age");
  74.             }
  75.         }

  76.         public string Address
  77.         {
  78.             get { return _address; }
  79.             set
  80.             {
  81.                 if (value == _address) return;
  82.                 _address = value;
  83.                 OnPropertyChanged("Address");
  84.             }
  85.         }
  86.         #endregion

  87.         #region INotifyPropertyChanged 接口实现
  88.         public event PropertyChangedEventHandler PropertyChanged;

  89.         protected void OnPropertyChanged(string name)
  90.         {
  91.             if (PropertyChanged != null)
  92.                 PropertyChanged(this, new PropertyChangedEventArgs(name));
  93.         }
  94.         #endregion

  95.     }
  96. }
复制代码
cobra - 2009-9-11 12:27:00
3、完成校验错误处理程序
  1.   #region 校验错误处理程序
  2.         private void TextBox_BindingValidationError(object sender, ValidationErrorEventArgs e)
  3.         {
  4.            
  5.             if (e.Action == ValidationErrorEventAction.Added)
  6.             {
  7.               //((Control)e.OriginalSource).Background = new SolidColorBrush(Colors.Red);
  8.               //((Control)e.OriginalSource).SetValue(ToolTipService.ToolTipProperty, e.Error.Exception.Message);
  9.               //((Control)e.OriginalSource).Focus();
  10.               this.Dispatcher.BeginInvoke(() => HtmlPage.Window.Alert(e.Error.Exception.Message));

  11.              
  12.             }
  13.             else if (e.Action == ValidationErrorEventAction.Removed)
  14.             {
  15.                 //((Control)e.OriginalSource).Background = new SolidColorBrush(Colors.White);
  16.                 //((Control)e.OriginalSource).SetValue(ToolTipService.ToolTipProperty, null);
  17.             }

  18.         }
  19.         #endregion
复制代码
Page.xaml.cs全部代码如下:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Documents;
  8. using System.Windows.Input;
  9. using System.Windows.Media;
  10. using System.Windows.Media.Animation;
  11. using System.Windows.Shapes;
  12. using System.Windows.Browser; //因为要使用HtmlPage.Window.Alert(message));

  13. namespace SLApplicationDataTest
  14. {
  15.     public partial class Page : UserControl
  16.     {
  17.         People mypeople;
  18.         public Page()
  19.         {
  20.             InitializeComponent();

  21.             this.addButton.Click += new RoutedEventHandler(addButton_Click);
  22.             this.deleteButton.Click += new RoutedEventHandler(deleteButton_Click);
  23.             this.dgPeople.KeyDown += new KeyEventHandler(peopleDataGrid_KeyDown);



  24.             Loaded += new RoutedEventHandler(Page_Loaded);
  25.         }

  26.         private void Page_Loaded(object sender, RoutedEventArgs e)
  27.         {
  28.             取得数据源数据并绑定到DataGrid控件上#region 取得数据源数据并绑定到DataGrid控件上
  29.             mypeople = People.GetTestData();
  30.             this.dgPeople.ItemsSource = mypeople;
  31.             #endregion

  32.         }

  33.         #region 通过按钮添加新记录行
  34.         void addButton_Click(object sender, RoutedEventArgs e)
  35.         {
  36.             mypeople.Add(new Person());
  37.         }
  38.         #endregion

  39.         #region 通过按钮删除记录
  40.         void deleteButton_Click(object sender, RoutedEventArgs e)
  41.         {
  42.             DeletePerson();
  43.         }
  44.         #endregion

  45.         #region 删除记录子程序
  46.         private void DeletePerson()
  47.         {
  48.             if (null == this.dgPeople.SelectedItem)
  49.             {
  50.                 return;
  51.             }
  52.             Person person = this.dgPeople.SelectedItem as Person;
  53.             if (null == person)
  54.             {
  55.                 return;
  56.             }
  57.             mypeople.Remove(person);
  58.         }
  59.         #endregion

  60.         #region 处理键盘响应事件
  61.         void peopleDataGrid_KeyDown(object sender, KeyEventArgs e)
  62.         {
  63.             如果是Insert键,则做插入新行操作#region 如果是Insert键,则做插入新行操作
  64.             if (Key.Insert == e.Key)
  65.             {
  66.                 mypeople.Add(new Person());
  67.             }
  68.             #endregion

  69.             如果是Delete键,则做删除操作#region 如果是Delete键,则做删除操作
  70.             if (Key.Delete == e.Key)
  71.             {
  72.                 DeletePerson();
  73.             }
  74.             #endregion
  75.         }
  76.         #endregion


  77.         #region 校验错误处理程序
  78.         private void TextBox_BindingValidationError(object sender, ValidationErrorEventArgs e)
  79.         {
  80.            
  81.             if (e.Action == ValidationErrorEventAction.Added)
  82.             {
  83.                 //如果校验出错,则抛出错误提示窗口
  84.               /**/////((Control)e.OriginalSource).Background = new SolidColorBrush(Colors.Red);
  85.               ////((Control)e.OriginalSource).SetValue(ToolTipService.ToolTipProperty, e.Error.Exception.Message);
  86.               ////((Control)e.OriginalSource).Focus();
  87.               this.Dispatcher.BeginInvoke(() => HtmlPage.Window.Alert(e.Error.Exception.Message));

  88.              
  89.             }
  90.             else if (e.Action == ValidationErrorEventAction.Removed)
  91.             {
  92.                 //如果校验通过,则做如下处理
  93.                 /**/////((Control)e.OriginalSource).Background = new SolidColorBrush(Colors.White);
  94.                 ////((Control)e.OriginalSource).SetValue(ToolTipService.ToolTipProperty, null);
  95.             }

  96.         }
  97.         #endregion

  98.     }
  99. }
复制代码
运行效果如下:

附件: 1.png


附件: 2.png




文/wsdj
查看完整版本: SilverLight学习笔记--实际应用(一)(4):手把手建立一个Silverlight应用程序之同步数据校验1