本文将简单讲述Silverlight中的Binding数据时的数据验证。
NotifyOnValidationError:是否在出现异常/错误信息的时候激发BindingValidationError事件。
ValidatesOnExceptions:是否将异常信息作为错误信息显示出来。
ValidatesOnDataErrors:结合IDataErrorInfo接口以显示错误信息。
BindingValidationError:这是一个路由事件,当绑定数据的源对象A有错误的时候,抛出异常让此事件接收并且触发,当源对象A没有BindingValidationError事件的时候让其父对象的BindingValidationError事件接收并且触发。
首先我们写一个用户类,并且在属性中进行简单验证错误时抛出异常如下代码:
- public class User
- {
- private string m_UserName;
- public string UserName
- {
- get { return m_UserName; }
- set
- {
- if (value.Length < 3)
- {
- throw new Exception("用户名小于3个字符");
- }
- m_UserName = value;
- }
- }
- private string m_UserPwd;
- public string UserPwd
- {
- get { return m_UserPwd; }
- set
- {
- if (value.Length < 6)
- {
- throw new Exception("密码长度不能小于6");
- }
- m_UserPwd = value;
- }
- }
- }
然后我们来看Xaml代码演示一个登录时数据绑定的界面:
- <Grid x:Name="LayoutRoot" Background="White" >
- <Canvas Name="canvasUser" BindingValidationError="canvasUser_BindingValidationError"
- Loaded="canvasUser_Loaded">
- <sdk:Label Height="28" Name="lbpwd" Width="55" Canvas.Left="16" Canvas.Top="51"
- Content="密 码:" />
- <sdk:Label Canvas.Left="16" Canvas.Top="15" Height="28" Name="lbusername"
- Width="55" Content="用户名:" />
- <TextBox x:Name="tbUserName" Width="88" Margin="10"
- Text="{Binding Path=UserName, Mode=TwoWay,
- NotifyOnValidationError=True,ValidatesOnExceptions=True}"
- Canvas.Left="91" Canvas.Top="5" />
- <TextBox x:Name="tbUserPwd" Width="88" Margin="10"
- Text="{Binding Path=UserPwd, Mode=TwoWay,
- NotifyOnValidationError=False,ValidatesOnExceptions=True}"
- Canvas.Left="91" Canvas.Top="45" />
- <Button Height="30" Width="70" Content="提 交"
- Canvas.Left="54" Canvas.Top="93" />
- </Canvas>
- </Grid>
最后将User类绑定到前台界面原始,并且描述BindingValidationError事件时将TextBox边框变为红色。
- public partial class MainPage : UserControl
- {
- public MainPage()
- {
- InitializeComponent();
- }
- private void canvasUser_BindingValidationError(object sender, ValidationErrorEventArgs e)
- {
- TextBox tb = e.OriginalSource as TextBox;
- if (e.Action == ValidationErrorEventAction.Added)
- {
- tb.BorderBrush = new SolidColorBrush(Colors.Red);
- }
- else if (e.Action == ValidationErrorEventAction.Removed)
- {
- tb.BorderBrush = new SolidColorBrush(Colors.White);
- }
- }
- private void canvasUser_Loaded(object sender, RoutedEventArgs e)
- {
- this.canvasUser.DataContext = new User();
- }
- }
实现效果如下图,在输入非正确的字符数目的时候会自动提示错误,如需源码请点击SLBinding2.rar 下载。
转载于:https://blog.51cto.com/chengxingliang/827107