Silverlight开发历程-(数据验证)

      Silverlight 支持基本的数据验证,在TwoWay双向绑定中可以验证你输入数据的合法性。

        要验证数据,必须要将绑定对象上的ValidatesOnExceptions属性设置为True,NotifyOnValidationError属性设置为True。ValidatesOnExceptions的作用是通知绑定引擎在发生异常时创建验证错误。NotifyOnValidationError属性的作用是在发生异常时引发BindingValidationError事件。

      下面是代码,首先创建一个Book_Val类如下代码:

       

ublic class Book_Val : INotifyPropertyChanged
    {
        //book继承了INotifyPropertyChanged,实现了PropertyChanged事件,并对Price属性添加了监视
        /// <summary>
        /// 标题
        /// </summary>
        public string Title
        { get; set; }

        private double _price;
        /// <summary>
        /// 价格
        /// </summary>
        public double Price
        {
            get { return _price; }
            set
            {
                if (value < 0)
                {
                    throw new Exception("单价不能为负数,请重新输入!");
                }
                _price = value;
                NotifyProperyChanged("Price");
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyProperyChanged(string PropertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
            }
        }
    }


在XAML中把价格绑定到TextBox上

XAML:

    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="50" />
            <RowDefinition Height="50"/>
            <RowDefinition Height="50"/>
            <RowDefinition Height="70"/>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal" VerticalAlignment="Center"  Grid.Row="0" Width="300">
            <TextBlock FontSize="17" Text="书名:" Width="70" Margin="10,0,0,0"  />
            <TextBlock x:Name="txb_Title" FontSize="17" Text="{Binding Title,Mode=OneWay}"  />
        </StackPanel>
        <StackPanel Orientation="Horizontal" VerticalAlignment="Center"  Grid.Row="1" Width="300">
            <TextBlock FontSize="17" Text="单价:" Width="70" Margin="10,0,0,0"  />
            <TextBlock x:Name="txb_OldPrice" FontSize="17" Text="{Binding Price,Mode=TwoWay}"  />
        </StackPanel>
        <StackPanel Orientation="Horizontal" VerticalAlignment="Center"  Grid.Row="2" Width="300">
            <TextBlock FontSize="17" Text="新单价:" Width="70" Margin="10,0,0,0"  />
            <TextBox x:Name="txt_Price"  Width="200" Text="{Binding Price,Mode=TwoWay,NotifyOnValidationError=True, ValidatesOnExceptions=True}" 
                     BindingValidationError="txt_Price_BindingValidationError" FontSize="17"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal" VerticalAlignment="Center"  HorizontalAlignment="Center" Width="300" Grid.Row="3">
           <Button x:Name="btn_Edit" Click="btn_Edit_Click"  Content="修 改" FontSize="17" Width="100" />
        </StackPanel>
    </Grid>


后台C#代码:

        Book_Val book = new Book_Val();
        public DataValidation()
        {
            InitializeComponent();
            book.Title = "Silverlight开发历程!";
            book.Price = 80;
            txb_Title.DataContext = book;
            txb_OldPrice.DataContext = book;
            txt_Price.DataContext = book;
        }

        private void txt_Price_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            //修改txt_Price背景框的颜色
            if (e.Action == ValidationErrorEventAction.Added)
            {
                txt_Price.Background = new SolidColorBrush(Colors.Red);
            }
            else if (e.Action == ValidationErrorEventAction.Removed)
            {
                txt_Price.Background = new SolidColorBrush(Colors.White);
            }
        }

        private void btn_Edit_Click(object sender, RoutedEventArgs e)
        {

            book.Price = Convert.ToDouble(txt_Price.Text);
        }


运行如结果:

出错的时候报错:

 

这个例子就完了,但是个人感觉不太好因为在调试环境下他总是会报出异常错误,即使在平常浏览状态下,他仍然会报出调试窗口,我也在网上找了资料,很多都是把调试功能

给去掉了,并没有从根本上解决这个问题,所以个人感觉这个验证直接throw出异常不太好,也许是我个人没有学习到位,希望朋友们如果知道其它更好的验证方法的话,请给我留言,谢谢。

posted @ 2011-10-25 17:36  Bodi  阅读(156)  评论(0编辑  收藏  举报