Silverlight Telerik控件学习:数据录入、数据验证
生活随笔
收集整理的這篇文章主要介紹了
Silverlight Telerik控件学习:数据录入、数据验证
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
相信很多人都聽(tīng)說(shuō)過(guò)這句名言:garbage in ,garbage out ! 數(shù)據(jù)錄入不規(guī)范(或錯(cuò)誤)就象一顆定時(shí)炸彈,遲早會(huì)給系統(tǒng)帶來(lái)麻煩,所以在數(shù)據(jù)錄入時(shí)做好驗(yàn)證是很有必要的。 相對(duì)傳統(tǒng)asp.net開(kāi)發(fā)而言,SL4中的數(shù)據(jù)驗(yàn)證要輕松很多(主要得益于Xaml的Binding特性),步驟如下:
1、定義業(yè)務(wù)Model類(lèi)時(shí),在需要驗(yàn)證的屬性setter中,寫(xiě)好業(yè)務(wù)邏輯,對(duì)于不合規(guī)范的value,要拋出異常! 同時(shí)切記Model類(lèi)要實(shí)現(xiàn)INotifyPropertyChanged接口,同時(shí)每個(gè)setter方法的最后,要顯示調(diào)用OnPropertyChanged方法 比如,我們要做一個(gè)會(huì)員注冊(cè)填寫(xiě)資料的Form,需要一個(gè)UserModel類(lèi),為了方便,先定義一個(gè)通用的基類(lèi)BusinessBaseObject.cs using System.ComponentModel; namespace BusinessObject {public class BusinessBaseObject : INotifyPropertyChanged{public event PropertyChangedEventHandler PropertyChanged;/// <summary>/// 屬性改變時(shí)觸發(fā)事件/// </summary>/// <param name="propertyName">Property that changed.</param>protected void OnPropertyChanged(string propertyName){PropertyChangedEventHandler handler = PropertyChanged;if (null != handler){handler.Invoke(this, new PropertyChangedEventArgs(propertyName));}}} } 再來(lái)定義UserModel.cs #define DEV //#undef DEV using System; using Common.Silverlight;namespace BusinessObject {public class UserModel : BusinessBaseObject{private string _userName;public string UserName{get { return _userName; }set{#if DEVif (string.IsNullOrEmpty(value)){throw new Exception("用戶(hù)名不能為空");}if (!(value.IsEmail() || value.IsUserName())){throw new Exception("格式錯(cuò)誤,正確示例如:abc007");} #endif_userName = value;OnPropertyChanged("UserName");}}private bool? _sex = null;public bool? Sex{get { return _sex; }set { #if DEVif (!_sex.HasValue) {throw new Exception("請(qǐng)選擇性別");} #endif_sex = value;OnPropertyChanged("UserName");}} private string _password;public string Password{get { return _password; }set{if (string.IsNullOrEmpty(value)){throw new Exception("密碼不能為空!");} #if DEVif (value.Length < 6){throw new Exception("密碼長(zhǎng)度不得低于6位");} #endif_password = value;OnPropertyChanged("Password");}}private string _password2;public string Password2{get { return _password2; }set{if (string.IsNullOrEmpty(value)){throw new Exception("密碼不能為空");} #if DEVif (value!=this._password){throw new Exception("重復(fù)密碼必須與密碼輸入一致");} #endif_password2 = value;OnPropertyChanged("Password2");}}private DateTime _birthday;public DateTime Birthday{get { return _birthday; }set{ #if DEVif (value <= DateTime.Now.AddYears(-100)){throw new Exception("我們不贊同百歲以上的老人上網(wǎng)");} #endif_birthday = value;OnPropertyChanged("Birthday");}}private string _email;public string Email{get { return _email; }set{ #if DEVif (!string.IsNullOrEmpty(value) && !value.IsEmail()){throw new Exception("格式錯(cuò)誤,正確示例如:yjmyzz@126.com");} #endif_email = value;OnPropertyChanged("Email");}}private string _telephone;public string Telephone{get { return _telephone; }set{ #if DEVif (!value.IsTel()){throw new Exception("格式錯(cuò)誤,正確示例如:021-38889088或021-36559079-023");} #endif_telephone = value;OnPropertyChanged("Telephone");}}private string _mobile = "";public string Mobile{get { return _mobile; }set{#if DEVif (!value.IsMobile()){throw new Exception("格式錯(cuò)誤,正確示例如:13916752109");}#endifthis._mobile = value;OnPropertyChanged("Mobile");}}private bool _agree = false;public bool Agree{get { return _agree; }set { #if DEVif (value==false){throw new Exception("您必須同意注冊(cè)條款!");} #endifthis._agree = value;OnPropertyChanged("Agree");}}private int _internetAge = 0;public int InternetAge{get { return _internetAge; }set { #if DEVif (_internetAge<0){throw new Exception("網(wǎng)齡不能為負(fù)數(shù)");}#endif_internetAge = value;OnPropertyChanged("InternetAge");}}private TimeRange _internetHours = new TimeRange();public TimeRange InternetHours{get { return _internetHours; }set { _internetHours = value;OnPropertyChanged("InternetHours");}}}public class TimeRange : BusinessBaseObject{private TimeSpan start = DateTime.Now.TimeOfDay + TimeSpan.FromMinutes(5);private TimeSpan end = DateTime.Now.TimeOfDay + TimeSpan.FromHours(1);private const int MaximumRangeSpan = 6;public TimeSpan Start{get{return this.start;}set{if (value < DateTime.Now.TimeOfDay){throw new Exception("上網(wǎng)時(shí)段起始值必須在當(dāng)前時(shí)間5分鐘以后");//注:這個(gè)限定只是為了演示數(shù)據(jù)驗(yàn)證,并無(wú)實(shí)際意義}if (End - value > TimeSpan.FromHours(MaximumRangeSpan)){ThrowOutOfRangeException();}this.start = value;OnPropertyChanged("Start");}}public TimeSpan End{get{return this.end;}set{if (value < DateTime.Now.TimeOfDay){throw new Exception("上網(wǎng)時(shí)段截止值不能早于當(dāng)前時(shí)間");//注:這個(gè)限定只是為了演示數(shù)據(jù)驗(yàn)證,并無(wú)實(shí)際意義}if (value - Start > TimeSpan.FromHours(MaximumRangeSpan)){ThrowOutOfRangeException();}this.end = value;OnPropertyChanged("End");}}private static void ThrowOutOfRangeException(){string message = string.Format("上網(wǎng)時(shí)間不能大于 {0} 小時(shí)", MaximumRangeSpan);throw new Exception(message);}} } 注:因?yàn)镾l中的數(shù)據(jù)驗(yàn)證實(shí)際上是通過(guò)拋異常將提示信息扔到前端的,這會(huì)導(dǎo)致在調(diào)試時(shí)vs.net不斷的被異常信息所打斷,這個(gè)有點(diǎn)煩人,所以我用了#define/#undef/#if /#endif 條件編譯的小技巧,在調(diào)試期先不處理異常,等其它業(yè)務(wù)邏輯寫(xiě)完后,最后再加上#undef,進(jìn)行數(shù)據(jù)驗(yàn)證測(cè)試。
2、xaml界面部分,用Binding將各控件與Model實(shí)例的屬性關(guān)聯(lián),對(duì)于指定長(zhǎng)度和指定輸入字符集的字段(比如:18位身份證號(hào),手機(jī)號(hào)之類(lèi)),最適合用RadMaskedTextBox,示例如下: <UserControl xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:validation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input"xmlns:System="clr-namespace:System;assembly=mscorlib" xmlns:Telerik_Windows_Controls_MaskedTextBox="clr-namespace:Telerik.Windows.Controls.MaskedTextBox;assembly=Telerik.Windows.Controls.Input" xmlns:Telerik_Windows_Controls_Chromes="clr-namespace:Telerik.Windows.Controls.Chromes;assembly=Telerik.Windows.Controls" x:Class="Telerik.Sample.Validataion"mc:Ignorable="d"d:DesignHeight="600" d:DesignWidth="600"><UserControl.Resources> <Style x:Key="PasswordBoxToRadMaskTextBoxStyle" TargetType="PasswordBox"><Setter Property="BorderThickness" Value="1"/><Setter Property="Background" Value="#FFFFFFFF"/><Setter Property="Foreground" Value="#FF000000"/><Setter Property="Padding" Value="2"/><Setter Property="BorderBrush" Value="#FF848484" /> <Setter Property="Template"><Setter.Value><ControlTemplate TargetType="PasswordBox"><Grid x:Name="RootElement"><VisualStateManager.VisualStateGroups><VisualStateGroup x:Name="CommonStates"><VisualState x:Name="Normal"/><VisualState x:Name="MouseOver"><Storyboard><ColorAnimation Duration="0" To="#FFFFC92B" Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Border"/></Storyboard></VisualState><VisualState x:Name="Disabled"><Storyboard><DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="DisabledVisualElement"/></Storyboard></VisualState></VisualStateGroup><VisualStateGroup x:Name="FocusStates"><VisualState x:Name="Focused"><Storyboard><ColorAnimation Duration="0" To="#FFFFC92B" Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Border"/></Storyboard></VisualState><VisualState x:Name="Unfocused"><Storyboard><ColorAnimation Duration="0" To="{TemplateBinding BorderBrush}" Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Border"/></Storyboard></VisualState></VisualStateGroup><VisualStateGroup x:Name="ValidationStates"><VisualState x:Name="Valid"/><VisualState x:Name="InvalidUnfocused"><Storyboard><ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="ValidationErrorElement"><DiscreteObjectKeyFrame KeyTime="0"><DiscreteObjectKeyFrame.Value><Visibility>Visible</Visibility></DiscreteObjectKeyFrame.Value></DiscreteObjectKeyFrame></ObjectAnimationUsingKeyFrames></Storyboard></VisualState><VisualState x:Name="InvalidFocused"><Storyboard><ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="ValidationErrorElement"><DiscreteObjectKeyFrame KeyTime="0"><DiscreteObjectKeyFrame.Value><Visibility>Visible</Visibility></DiscreteObjectKeyFrame.Value></DiscreteObjectKeyFrame></ObjectAnimationUsingKeyFrames><ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="IsOpen" Storyboard.TargetName="validationTooltip"><DiscreteObjectKeyFrame KeyTime="0"><DiscreteObjectKeyFrame.Value><System:Boolean>True</System:Boolean></DiscreteObjectKeyFrame.Value></DiscreteObjectKeyFrame></ObjectAnimationUsingKeyFrames></Storyboard></VisualState></VisualStateGroup></VisualStateManager.VisualStateGroups><Border x:Name="Border" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="1" Opacity="1" BorderBrush="{TemplateBinding BorderBrush}"> <Border x:Name="ContentElement" Margin="{TemplateBinding Padding}"/> </Border><Border x:Name="DisabledVisualElement" BorderBrush="#A5F7F7F7" BorderThickness="{TemplateBinding BorderThickness}" Background="#A5F7F7F7" IsHitTestVisible="False" Opacity="0"/><Border x:Name="ValidationErrorElement" BorderBrush="#FFDB000C" BorderThickness="1" CornerRadius="1" Visibility="Collapsed"><ToolTipService.ToolTip><ToolTip x:Name="validationTooltip" DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}" Placement="Right" PlacementTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}" Template="{StaticResource ValidationToolTipTemplate}"><ToolTip.Triggers><EventTrigger RoutedEvent="Canvas.Loaded"><BeginStoryboard><Storyboard><ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="IsHitTestVisible" Storyboard.TargetName="validationTooltip"><DiscreteObjectKeyFrame KeyTime="0"><DiscreteObjectKeyFrame.Value><System:Boolean>true</System:Boolean></DiscreteObjectKeyFrame.Value></DiscreteObjectKeyFrame></ObjectAnimationUsingKeyFrames></Storyboard></BeginStoryboard></EventTrigger></ToolTip.Triggers></ToolTip></ToolTipService.ToolTip><Grid Background="Transparent" HorizontalAlignment="Right" Height="12" Margin="1,-4,-4,0" VerticalAlignment="Top" Width="12"><Path Data="M 1,0 L6,0 A 2,2 90 0 1 8,2 L8,7 z" Fill="#FFDC000C" Margin="1,3,0,0"/><Path Data="M 0,0 L2,0 L 8,6 L8,8" Fill="#ffffff" Margin="1,3,0,0"/></Grid></Border></Grid></ControlTemplate></Setter.Value></Setter></Style></UserControl.Resources><Grid x:Name="LayoutRoot" Background="White"><Grid VerticalAlignment="Center" HorizontalAlignment="Center" Width="500"><Grid.RowDefinitions><RowDefinition Height="30" /><RowDefinition Height="30" /><RowDefinition Height="30" /><RowDefinition Height="30" /><RowDefinition Height="30" /><RowDefinition Height="30" /><RowDefinition Height="30" /><RowDefinition Height="30" /><RowDefinition Height="30" /><RowDefinition Height="50" /><RowDefinition Height="30" /><RowDefinition Height="Auto"/><RowDefinition Height="30" /></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="100" /><ColumnDefinition Width="400" MinWidth="200"/></Grid.ColumnDefinitions><TextBlock Grid.Row="0" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="用戶(hù)名:"/></TextBlock><telerik:RadMaskedTextBox Grid.Column="1" Grid.Row="0" x:Name="txtUserName" VerticalAlignment="Center" GotFocus="RadMaskedTextBox_GotFocus"Value="{Binding UserName, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" EmptyContent="格式:2-50位字母、數(shù)字、下線線組合" Width="250" MaskType="None" HorizontalAlignment="Left" /><TextBlock Grid.Row="1" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="密碼:"/></TextBlock><PasswordBox Grid.Row="1" Grid.Column="1" Width="250" MaxLength="32" HorizontalAlignment="Left" VerticalAlignment="Center" Password="{Binding Password, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" x:Name="txtPwd" Style="{StaticResource PasswordBoxToRadMaskTextBoxStyle}" /><TextBlock Grid.Row="2" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="重復(fù)密碼:"/></TextBlock><PasswordBox Grid.Row="2" Grid.Column="1" Width="250" HorizontalAlignment="Left" VerticalAlignment="Center" Password="{Binding Password2, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" x:Name="txtPwd2" Style="{StaticResource PasswordBoxToRadMaskTextBoxStyle}"/><TextBlock Grid.Row="3" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="性別:"/></TextBlock><StackPanel Grid.Row="3" Grid.Column="1" Orientation="Horizontal" ><telerik:RadComboBox x:Name="rcboSex" Width="250" SelectedIndex="2"><telerik:RadComboBoxItem Content="男" /><telerik:RadComboBoxItem Content="女" /><telerik:RadComboBoxItem Content="保密" /></telerik:RadComboBox></StackPanel><TextBlock Grid.Row="4" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="電話號(hào)碼:"/></TextBlock><telerik:RadMaskedTextBox Grid.Column="1" Grid.Row="4" MaskType="None" ValueChanging="txtTel_ValueChanging" x:Name="txtTel" VerticalAlignment="Center" GotFocus="RadMaskedTextBox_GotFocus"Value="{Binding Telephone, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" EmptyContent="格式:區(qū)號(hào)-電話號(hào)碼-分機(jī)號(hào)(可選)" Width="250" HorizontalAlignment="Left" /><TextBlock Grid.Row="5" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="手機(jī)號(hào)碼:"/></TextBlock><telerik:RadMaskedTextBox Grid.Column="1" Grid.Row="5" Mask="###########" x:Name="txtMobile" VerticalAlignment="Center" GotFocus="RadMaskedTextBox_GotFocus"Value="{Binding Mobile, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" EmptyContent="比如:13916752109" Width="250" HorizontalAlignment="Left" /><TextBlock Grid.Row="6" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="電子郵箱:"/></TextBlock><telerik:RadMaskedTextBox Grid.Column="1" Grid.Row="6" MaskType="None" x:Name="txtEmail" VerticalAlignment="Center" GotFocus="RadMaskedTextBox_GotFocus"Value="{Binding Email, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" EmptyContent="比如:youname@sample.com" Width="250" HorizontalAlignment="Left" /><TextBlock Grid.Row="7" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="出生日期:"/></TextBlock><telerik:RadDatePicker Grid.Column="1" Grid.Row="7"SelectedDate="{Binding Birthday, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"Width="250" Height="22" HorizontalAlignment="Left" x:Name="rdp_Birthday" /><TextBlock Grid.Row="8" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="網(wǎng)齡:"/></TextBlock><telerik:RadNumericUpDown Grid.Row="8" Grid.Column="1" Minimum="0" Maximum="30"Value="{Binding InternetAge, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"Loaded="btnInternetAge_Loaded" SmallChange="1" HorizontalAlignment="Left" VerticalAlignment="Center"Width="250" x:Name="btnInternetAge" /><TextBlock Grid.Row="9" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="經(jīng)常上網(wǎng)時(shí)段:"/></TextBlock><StackPanel Grid.Row="9" Grid.Column="1"><telerik:RadSlider IsSelectionRangeEnabled="True"Style="{StaticResource RadSliderStyle}" Minimum="0" Maximum="1380"TickFrequency="240"SelectionStart="{Binding InternetHours.Start, Converter={StaticResource TimeConverter}, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"SelectionEnd="{Binding InternetHours.End, Converter={StaticResource TimeConverter}, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"TickPlacement="TopLeft" Width="250" HorizontalAlignment="Left"><telerik:RadSlider.TickTemplate><DataTemplate><Grid><TextBlock FontSize="8" UseLayoutRounding="True"Text="{Binding Converter={StaticResource TickValueConverter}}" /></Grid></DataTemplate></telerik:RadSlider.TickTemplate></telerik:RadSlider><StackPanel Orientation="Horizontal" Width="200"UseLayoutRounding="True" HorizontalAlignment="Left" Margin="25,0,0,0"><TextBlock FontSize="8"Text="{Binding InternetHours.Start, Converter={StaticResource TimeToTextConverter}}" /><TextBlock FontSize="8" Text=" - " /><TextBlock FontSize="8"Text="{Binding InternetHours.End, Converter={StaticResource TimeToTextConverter}}" /></StackPanel></StackPanel><telerik:RadToggleButton Grid.Row="10" Width="250" HorizontalAlignment="Left" Grid.Column="1" Content="我同意注冊(cè)條款" VerticalAlignment="Center" IsChecked="{Binding Agree, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" x:Name="btnAgree" /><validation:ValidationSummary Grid.Row="11" Grid.Column="0" Grid.ColumnSpan="2" AllowDrop="True" Header="提示" x:Name="ValidationSummary1"/><telerik:RadButton Content="提交" Grid.Row="12" Grid.Column="1" Height="22" Width="65" HorizontalAlignment="Left" Click="btnSubmit_Click" x:Name="btnSubmit" Margin="190,0,0,0"/></Grid></Grid> </UserControl>
3、Xaml.cs后端部分 using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System; using BusinessObject; using Telerik.Windows.Controls; using System.Text.RegularExpressions;namespace Telerik.Sample {public partial class Validataion : UserControl{UserModel model = new UserModel();public Validataion(){InitializeComponent();this.Loaded += new RoutedEventHandler(Validataion_Loaded);}void Validataion_Loaded(object sender, RoutedEventArgs e){ this.DataContext = model;#region//model.Mobile = "13916752109";//model.UserName = "yjmyzz";//model.Password = "123456";//model.InternetAge = 10;//model.Birthday = new DateTime(1979, 6, 5);//model.Telephone = "021-36559079";//model.Email = "yjmyzz@126.com";//model.Password2 = model.Password;#endregion#region 有錯(cuò)誤時(shí),不允許提交(必須配合輸入框獲取焦點(diǎn)時(shí),自動(dòng)激活驗(yàn)證)Binding binding = new Binding("HasErrors");binding.Source = ValidationSummary1;binding.Converter = new HasErrorsToIsEnabledConverter();this.btnSubmit.SetBinding(Button.IsEnabledProperty, binding);#endregion}private void RadMaskedTextBox_GotFocus(object sender, RoutedEventArgs e){ //文本框獲得焦點(diǎn)時(shí),自動(dòng)激活實(shí)時(shí)驗(yàn)證UpdateBindingExpression(sender as DependencyObject, RadMaskedTextBox.ValueProperty);}private void UpdateBindingExpression(DependencyObject obj, DependencyProperty prop){BindingExpression b = obj.ReadLocalValue(prop) as BindingExpression;b.UpdateSource();}private void btnSubmit_Click(object sender, RoutedEventArgs e){ //顯式驗(yàn)證必填項(xiàng)UpdateBindingExpression(txtUserName, RadMaskedTextBox.ValueProperty);UpdateBindingExpression(txtPwd, PasswordBox.PasswordProperty);UpdateBindingExpression(txtPwd2, PasswordBox.PasswordProperty);UpdateBindingExpression(this.btnAgree, RadToggleButton.IsCheckedProperty);}private void btnInternetAge_Loaded(object sender, RoutedEventArgs e){//去掉小數(shù)位(sender as RadNumericUpDown).NumberFormatInfo.NumberDecimalDigits = 0;}private void txtTel_ValueChanging(object sender, RadMaskedTextBoxValueChangingEventArgs e){ //只能輸入"0-9"和下劃線e.Handled = new Regex(@"^[\d-]{0,}$").IsMatch(e.NewMaskedText) == false;}} }
1、定義業(yè)務(wù)Model類(lèi)時(shí),在需要驗(yàn)證的屬性setter中,寫(xiě)好業(yè)務(wù)邏輯,對(duì)于不合規(guī)范的value,要拋出異常! 同時(shí)切記Model類(lèi)要實(shí)現(xiàn)INotifyPropertyChanged接口,同時(shí)每個(gè)setter方法的最后,要顯示調(diào)用OnPropertyChanged方法 比如,我們要做一個(gè)會(huì)員注冊(cè)填寫(xiě)資料的Form,需要一個(gè)UserModel類(lèi),為了方便,先定義一個(gè)通用的基類(lèi)BusinessBaseObject.cs using System.ComponentModel; namespace BusinessObject {public class BusinessBaseObject : INotifyPropertyChanged{public event PropertyChangedEventHandler PropertyChanged;/// <summary>/// 屬性改變時(shí)觸發(fā)事件/// </summary>/// <param name="propertyName">Property that changed.</param>protected void OnPropertyChanged(string propertyName){PropertyChangedEventHandler handler = PropertyChanged;if (null != handler){handler.Invoke(this, new PropertyChangedEventArgs(propertyName));}}} } 再來(lái)定義UserModel.cs #define DEV //#undef DEV using System; using Common.Silverlight;namespace BusinessObject {public class UserModel : BusinessBaseObject{private string _userName;public string UserName{get { return _userName; }set{#if DEVif (string.IsNullOrEmpty(value)){throw new Exception("用戶(hù)名不能為空");}if (!(value.IsEmail() || value.IsUserName())){throw new Exception("格式錯(cuò)誤,正確示例如:abc007");} #endif_userName = value;OnPropertyChanged("UserName");}}private bool? _sex = null;public bool? Sex{get { return _sex; }set { #if DEVif (!_sex.HasValue) {throw new Exception("請(qǐng)選擇性別");} #endif_sex = value;OnPropertyChanged("UserName");}} private string _password;public string Password{get { return _password; }set{if (string.IsNullOrEmpty(value)){throw new Exception("密碼不能為空!");} #if DEVif (value.Length < 6){throw new Exception("密碼長(zhǎng)度不得低于6位");} #endif_password = value;OnPropertyChanged("Password");}}private string _password2;public string Password2{get { return _password2; }set{if (string.IsNullOrEmpty(value)){throw new Exception("密碼不能為空");} #if DEVif (value!=this._password){throw new Exception("重復(fù)密碼必須與密碼輸入一致");} #endif_password2 = value;OnPropertyChanged("Password2");}}private DateTime _birthday;public DateTime Birthday{get { return _birthday; }set{ #if DEVif (value <= DateTime.Now.AddYears(-100)){throw new Exception("我們不贊同百歲以上的老人上網(wǎng)");} #endif_birthday = value;OnPropertyChanged("Birthday");}}private string _email;public string Email{get { return _email; }set{ #if DEVif (!string.IsNullOrEmpty(value) && !value.IsEmail()){throw new Exception("格式錯(cuò)誤,正確示例如:yjmyzz@126.com");} #endif_email = value;OnPropertyChanged("Email");}}private string _telephone;public string Telephone{get { return _telephone; }set{ #if DEVif (!value.IsTel()){throw new Exception("格式錯(cuò)誤,正確示例如:021-38889088或021-36559079-023");} #endif_telephone = value;OnPropertyChanged("Telephone");}}private string _mobile = "";public string Mobile{get { return _mobile; }set{#if DEVif (!value.IsMobile()){throw new Exception("格式錯(cuò)誤,正確示例如:13916752109");}#endifthis._mobile = value;OnPropertyChanged("Mobile");}}private bool _agree = false;public bool Agree{get { return _agree; }set { #if DEVif (value==false){throw new Exception("您必須同意注冊(cè)條款!");} #endifthis._agree = value;OnPropertyChanged("Agree");}}private int _internetAge = 0;public int InternetAge{get { return _internetAge; }set { #if DEVif (_internetAge<0){throw new Exception("網(wǎng)齡不能為負(fù)數(shù)");}#endif_internetAge = value;OnPropertyChanged("InternetAge");}}private TimeRange _internetHours = new TimeRange();public TimeRange InternetHours{get { return _internetHours; }set { _internetHours = value;OnPropertyChanged("InternetHours");}}}public class TimeRange : BusinessBaseObject{private TimeSpan start = DateTime.Now.TimeOfDay + TimeSpan.FromMinutes(5);private TimeSpan end = DateTime.Now.TimeOfDay + TimeSpan.FromHours(1);private const int MaximumRangeSpan = 6;public TimeSpan Start{get{return this.start;}set{if (value < DateTime.Now.TimeOfDay){throw new Exception("上網(wǎng)時(shí)段起始值必須在當(dāng)前時(shí)間5分鐘以后");//注:這個(gè)限定只是為了演示數(shù)據(jù)驗(yàn)證,并無(wú)實(shí)際意義}if (End - value > TimeSpan.FromHours(MaximumRangeSpan)){ThrowOutOfRangeException();}this.start = value;OnPropertyChanged("Start");}}public TimeSpan End{get{return this.end;}set{if (value < DateTime.Now.TimeOfDay){throw new Exception("上網(wǎng)時(shí)段截止值不能早于當(dāng)前時(shí)間");//注:這個(gè)限定只是為了演示數(shù)據(jù)驗(yàn)證,并無(wú)實(shí)際意義}if (value - Start > TimeSpan.FromHours(MaximumRangeSpan)){ThrowOutOfRangeException();}this.end = value;OnPropertyChanged("End");}}private static void ThrowOutOfRangeException(){string message = string.Format("上網(wǎng)時(shí)間不能大于 {0} 小時(shí)", MaximumRangeSpan);throw new Exception(message);}} } 注:因?yàn)镾l中的數(shù)據(jù)驗(yàn)證實(shí)際上是通過(guò)拋異常將提示信息扔到前端的,這會(huì)導(dǎo)致在調(diào)試時(shí)vs.net不斷的被異常信息所打斷,這個(gè)有點(diǎn)煩人,所以我用了#define/#undef/#if /#endif 條件編譯的小技巧,在調(diào)試期先不處理異常,等其它業(yè)務(wù)邏輯寫(xiě)完后,最后再加上#undef,進(jìn)行數(shù)據(jù)驗(yàn)證測(cè)試。
2、xaml界面部分,用Binding將各控件與Model實(shí)例的屬性關(guān)聯(lián),對(duì)于指定長(zhǎng)度和指定輸入字符集的字段(比如:18位身份證號(hào),手機(jī)號(hào)之類(lèi)),最適合用RadMaskedTextBox,示例如下: <UserControl xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:validation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input"xmlns:System="clr-namespace:System;assembly=mscorlib" xmlns:Telerik_Windows_Controls_MaskedTextBox="clr-namespace:Telerik.Windows.Controls.MaskedTextBox;assembly=Telerik.Windows.Controls.Input" xmlns:Telerik_Windows_Controls_Chromes="clr-namespace:Telerik.Windows.Controls.Chromes;assembly=Telerik.Windows.Controls" x:Class="Telerik.Sample.Validataion"mc:Ignorable="d"d:DesignHeight="600" d:DesignWidth="600"><UserControl.Resources> <Style x:Key="PasswordBoxToRadMaskTextBoxStyle" TargetType="PasswordBox"><Setter Property="BorderThickness" Value="1"/><Setter Property="Background" Value="#FFFFFFFF"/><Setter Property="Foreground" Value="#FF000000"/><Setter Property="Padding" Value="2"/><Setter Property="BorderBrush" Value="#FF848484" /> <Setter Property="Template"><Setter.Value><ControlTemplate TargetType="PasswordBox"><Grid x:Name="RootElement"><VisualStateManager.VisualStateGroups><VisualStateGroup x:Name="CommonStates"><VisualState x:Name="Normal"/><VisualState x:Name="MouseOver"><Storyboard><ColorAnimation Duration="0" To="#FFFFC92B" Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Border"/></Storyboard></VisualState><VisualState x:Name="Disabled"><Storyboard><DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="DisabledVisualElement"/></Storyboard></VisualState></VisualStateGroup><VisualStateGroup x:Name="FocusStates"><VisualState x:Name="Focused"><Storyboard><ColorAnimation Duration="0" To="#FFFFC92B" Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Border"/></Storyboard></VisualState><VisualState x:Name="Unfocused"><Storyboard><ColorAnimation Duration="0" To="{TemplateBinding BorderBrush}" Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="Border"/></Storyboard></VisualState></VisualStateGroup><VisualStateGroup x:Name="ValidationStates"><VisualState x:Name="Valid"/><VisualState x:Name="InvalidUnfocused"><Storyboard><ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="ValidationErrorElement"><DiscreteObjectKeyFrame KeyTime="0"><DiscreteObjectKeyFrame.Value><Visibility>Visible</Visibility></DiscreteObjectKeyFrame.Value></DiscreteObjectKeyFrame></ObjectAnimationUsingKeyFrames></Storyboard></VisualState><VisualState x:Name="InvalidFocused"><Storyboard><ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="ValidationErrorElement"><DiscreteObjectKeyFrame KeyTime="0"><DiscreteObjectKeyFrame.Value><Visibility>Visible</Visibility></DiscreteObjectKeyFrame.Value></DiscreteObjectKeyFrame></ObjectAnimationUsingKeyFrames><ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="IsOpen" Storyboard.TargetName="validationTooltip"><DiscreteObjectKeyFrame KeyTime="0"><DiscreteObjectKeyFrame.Value><System:Boolean>True</System:Boolean></DiscreteObjectKeyFrame.Value></DiscreteObjectKeyFrame></ObjectAnimationUsingKeyFrames></Storyboard></VisualState></VisualStateGroup></VisualStateManager.VisualStateGroups><Border x:Name="Border" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="1" Opacity="1" BorderBrush="{TemplateBinding BorderBrush}"> <Border x:Name="ContentElement" Margin="{TemplateBinding Padding}"/> </Border><Border x:Name="DisabledVisualElement" BorderBrush="#A5F7F7F7" BorderThickness="{TemplateBinding BorderThickness}" Background="#A5F7F7F7" IsHitTestVisible="False" Opacity="0"/><Border x:Name="ValidationErrorElement" BorderBrush="#FFDB000C" BorderThickness="1" CornerRadius="1" Visibility="Collapsed"><ToolTipService.ToolTip><ToolTip x:Name="validationTooltip" DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}" Placement="Right" PlacementTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}" Template="{StaticResource ValidationToolTipTemplate}"><ToolTip.Triggers><EventTrigger RoutedEvent="Canvas.Loaded"><BeginStoryboard><Storyboard><ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="IsHitTestVisible" Storyboard.TargetName="validationTooltip"><DiscreteObjectKeyFrame KeyTime="0"><DiscreteObjectKeyFrame.Value><System:Boolean>true</System:Boolean></DiscreteObjectKeyFrame.Value></DiscreteObjectKeyFrame></ObjectAnimationUsingKeyFrames></Storyboard></BeginStoryboard></EventTrigger></ToolTip.Triggers></ToolTip></ToolTipService.ToolTip><Grid Background="Transparent" HorizontalAlignment="Right" Height="12" Margin="1,-4,-4,0" VerticalAlignment="Top" Width="12"><Path Data="M 1,0 L6,0 A 2,2 90 0 1 8,2 L8,7 z" Fill="#FFDC000C" Margin="1,3,0,0"/><Path Data="M 0,0 L2,0 L 8,6 L8,8" Fill="#ffffff" Margin="1,3,0,0"/></Grid></Border></Grid></ControlTemplate></Setter.Value></Setter></Style></UserControl.Resources><Grid x:Name="LayoutRoot" Background="White"><Grid VerticalAlignment="Center" HorizontalAlignment="Center" Width="500"><Grid.RowDefinitions><RowDefinition Height="30" /><RowDefinition Height="30" /><RowDefinition Height="30" /><RowDefinition Height="30" /><RowDefinition Height="30" /><RowDefinition Height="30" /><RowDefinition Height="30" /><RowDefinition Height="30" /><RowDefinition Height="30" /><RowDefinition Height="50" /><RowDefinition Height="30" /><RowDefinition Height="Auto"/><RowDefinition Height="30" /></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="100" /><ColumnDefinition Width="400" MinWidth="200"/></Grid.ColumnDefinitions><TextBlock Grid.Row="0" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="用戶(hù)名:"/></TextBlock><telerik:RadMaskedTextBox Grid.Column="1" Grid.Row="0" x:Name="txtUserName" VerticalAlignment="Center" GotFocus="RadMaskedTextBox_GotFocus"Value="{Binding UserName, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" EmptyContent="格式:2-50位字母、數(shù)字、下線線組合" Width="250" MaskType="None" HorizontalAlignment="Left" /><TextBlock Grid.Row="1" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="密碼:"/></TextBlock><PasswordBox Grid.Row="1" Grid.Column="1" Width="250" MaxLength="32" HorizontalAlignment="Left" VerticalAlignment="Center" Password="{Binding Password, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" x:Name="txtPwd" Style="{StaticResource PasswordBoxToRadMaskTextBoxStyle}" /><TextBlock Grid.Row="2" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="重復(fù)密碼:"/></TextBlock><PasswordBox Grid.Row="2" Grid.Column="1" Width="250" HorizontalAlignment="Left" VerticalAlignment="Center" Password="{Binding Password2, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" x:Name="txtPwd2" Style="{StaticResource PasswordBoxToRadMaskTextBoxStyle}"/><TextBlock Grid.Row="3" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="性別:"/></TextBlock><StackPanel Grid.Row="3" Grid.Column="1" Orientation="Horizontal" ><telerik:RadComboBox x:Name="rcboSex" Width="250" SelectedIndex="2"><telerik:RadComboBoxItem Content="男" /><telerik:RadComboBoxItem Content="女" /><telerik:RadComboBoxItem Content="保密" /></telerik:RadComboBox></StackPanel><TextBlock Grid.Row="4" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="電話號(hào)碼:"/></TextBlock><telerik:RadMaskedTextBox Grid.Column="1" Grid.Row="4" MaskType="None" ValueChanging="txtTel_ValueChanging" x:Name="txtTel" VerticalAlignment="Center" GotFocus="RadMaskedTextBox_GotFocus"Value="{Binding Telephone, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" EmptyContent="格式:區(qū)號(hào)-電話號(hào)碼-分機(jī)號(hào)(可選)" Width="250" HorizontalAlignment="Left" /><TextBlock Grid.Row="5" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="手機(jī)號(hào)碼:"/></TextBlock><telerik:RadMaskedTextBox Grid.Column="1" Grid.Row="5" Mask="###########" x:Name="txtMobile" VerticalAlignment="Center" GotFocus="RadMaskedTextBox_GotFocus"Value="{Binding Mobile, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" EmptyContent="比如:13916752109" Width="250" HorizontalAlignment="Left" /><TextBlock Grid.Row="6" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="電子郵箱:"/></TextBlock><telerik:RadMaskedTextBox Grid.Column="1" Grid.Row="6" MaskType="None" x:Name="txtEmail" VerticalAlignment="Center" GotFocus="RadMaskedTextBox_GotFocus"Value="{Binding Email, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" EmptyContent="比如:youname@sample.com" Width="250" HorizontalAlignment="Left" /><TextBlock Grid.Row="7" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="出生日期:"/></TextBlock><telerik:RadDatePicker Grid.Column="1" Grid.Row="7"SelectedDate="{Binding Birthday, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"Width="250" Height="22" HorizontalAlignment="Left" x:Name="rdp_Birthday" /><TextBlock Grid.Row="8" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="網(wǎng)齡:"/></TextBlock><telerik:RadNumericUpDown Grid.Row="8" Grid.Column="1" Minimum="0" Maximum="30"Value="{Binding InternetAge, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"Loaded="btnInternetAge_Loaded" SmallChange="1" HorizontalAlignment="Left" VerticalAlignment="Center"Width="250" x:Name="btnInternetAge" /><TextBlock Grid.Row="9" Grid.Column="0" TextAlignment="Right" VerticalAlignment="Center"><Run Text="經(jīng)常上網(wǎng)時(shí)段:"/></TextBlock><StackPanel Grid.Row="9" Grid.Column="1"><telerik:RadSlider IsSelectionRangeEnabled="True"Style="{StaticResource RadSliderStyle}" Minimum="0" Maximum="1380"TickFrequency="240"SelectionStart="{Binding InternetHours.Start, Converter={StaticResource TimeConverter}, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"SelectionEnd="{Binding InternetHours.End, Converter={StaticResource TimeConverter}, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"TickPlacement="TopLeft" Width="250" HorizontalAlignment="Left"><telerik:RadSlider.TickTemplate><DataTemplate><Grid><TextBlock FontSize="8" UseLayoutRounding="True"Text="{Binding Converter={StaticResource TickValueConverter}}" /></Grid></DataTemplate></telerik:RadSlider.TickTemplate></telerik:RadSlider><StackPanel Orientation="Horizontal" Width="200"UseLayoutRounding="True" HorizontalAlignment="Left" Margin="25,0,0,0"><TextBlock FontSize="8"Text="{Binding InternetHours.Start, Converter={StaticResource TimeToTextConverter}}" /><TextBlock FontSize="8" Text=" - " /><TextBlock FontSize="8"Text="{Binding InternetHours.End, Converter={StaticResource TimeToTextConverter}}" /></StackPanel></StackPanel><telerik:RadToggleButton Grid.Row="10" Width="250" HorizontalAlignment="Left" Grid.Column="1" Content="我同意注冊(cè)條款" VerticalAlignment="Center" IsChecked="{Binding Agree, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" x:Name="btnAgree" /><validation:ValidationSummary Grid.Row="11" Grid.Column="0" Grid.ColumnSpan="2" AllowDrop="True" Header="提示" x:Name="ValidationSummary1"/><telerik:RadButton Content="提交" Grid.Row="12" Grid.Column="1" Height="22" Width="65" HorizontalAlignment="Left" Click="btnSubmit_Click" x:Name="btnSubmit" Margin="190,0,0,0"/></Grid></Grid> </UserControl>
3、Xaml.cs后端部分 using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System; using BusinessObject; using Telerik.Windows.Controls; using System.Text.RegularExpressions;namespace Telerik.Sample {public partial class Validataion : UserControl{UserModel model = new UserModel();public Validataion(){InitializeComponent();this.Loaded += new RoutedEventHandler(Validataion_Loaded);}void Validataion_Loaded(object sender, RoutedEventArgs e){ this.DataContext = model;#region//model.Mobile = "13916752109";//model.UserName = "yjmyzz";//model.Password = "123456";//model.InternetAge = 10;//model.Birthday = new DateTime(1979, 6, 5);//model.Telephone = "021-36559079";//model.Email = "yjmyzz@126.com";//model.Password2 = model.Password;#endregion#region 有錯(cuò)誤時(shí),不允許提交(必須配合輸入框獲取焦點(diǎn)時(shí),自動(dòng)激活驗(yàn)證)Binding binding = new Binding("HasErrors");binding.Source = ValidationSummary1;binding.Converter = new HasErrorsToIsEnabledConverter();this.btnSubmit.SetBinding(Button.IsEnabledProperty, binding);#endregion}private void RadMaskedTextBox_GotFocus(object sender, RoutedEventArgs e){ //文本框獲得焦點(diǎn)時(shí),自動(dòng)激活實(shí)時(shí)驗(yàn)證UpdateBindingExpression(sender as DependencyObject, RadMaskedTextBox.ValueProperty);}private void UpdateBindingExpression(DependencyObject obj, DependencyProperty prop){BindingExpression b = obj.ReadLocalValue(prop) as BindingExpression;b.UpdateSource();}private void btnSubmit_Click(object sender, RoutedEventArgs e){ //顯式驗(yàn)證必填項(xiàng)UpdateBindingExpression(txtUserName, RadMaskedTextBox.ValueProperty);UpdateBindingExpression(txtPwd, PasswordBox.PasswordProperty);UpdateBindingExpression(txtPwd2, PasswordBox.PasswordProperty);UpdateBindingExpression(this.btnAgree, RadToggleButton.IsCheckedProperty);}private void btnInternetAge_Loaded(object sender, RoutedEventArgs e){//去掉小數(shù)位(sender as RadNumericUpDown).NumberFormatInfo.NumberDecimalDigits = 0;}private void txtTel_ValueChanging(object sender, RadMaskedTextBoxValueChangingEventArgs e){ //只能輸入"0-9"和下劃線e.Handled = new Regex(@"^[\d-]{0,}$").IsMatch(e.NewMaskedText) == false;}} }
運(yùn)行截圖:
在線演示地址:
http://img.24city.com/jimmy/sl4/controls/telerik.html
轉(zhuǎn)載于:https://www.cnblogs.com/yjmyzz/archive/2011/05/21/2053112.html
總結(jié)
以上是生活随笔為你收集整理的Silverlight Telerik控件学习:数据录入、数据验证的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: jscript换行等特殊字符
- 下一篇: MOSS2010站点大文件上传设置