8,735
社区成员
发帖
与我相关
我的任务
分享
<UserControl x:Class="SilverlightApplication1.SilverlightControl4"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White" ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Margin="5" Grid.Row="0">
<TextBlock x:Name="Title" FontSize="15" Height="30" Text="{Binding Title,Mode=OneWay}"/>
<TextBlock x:Name="Price" FontSize="15" Height="30" Text="{Binding Price,Mode=TwoWay}"/>
<!--NotifyOnValidationError:是否使用错误验证通知 ValidatesOnExceptions:是否报告验证错误-->
<TextBox x:Name="MyTextBox" Margin="5" Width="100" Height="30" FontSize="15" Text="{Binding Price,Mode=TwoWay,NotifyOnValidationError=True,ValidatesOnExceptions=True}" BindingValidationError="MyTextBox_BindingValidationError"></TextBox>
</StackPanel>
<Button Name="MyButton" Content="修改" Click="MyButton_Click" FontSize="15" Width="80" Height="30" Grid.Row="1"></Button>
</Grid>
</UserControl>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
namespace SilverlightApplication1
{
public partial class SilverlightControl4 : UserControl
{
Book book = new Book();
public SilverlightControl4()
{
InitializeComponent();
book.Title = "数据验证测试";
book.Price = 22.22;
this.Title.DataContext = book;
this.Price.DataContext = book;
this.MyTextBox.DataContext = book;
}
private void MyTextBox_BindingValidationError(object sender, ValidationErrorEventArgs e)
{
if (e.Action == ValidationErrorEventAction.Added)
{
MyTextBox.Background = new SolidColorBrush(Colors.Red);
}
else if (e.Action == ValidationErrorEventAction.Removed)
{
MyTextBox.Background = new SolidColorBrush(Colors.White);
}
}
private void MyButton_Click(object sender, RoutedEventArgs e)
{
book.Price = Convert.ToDouble(this.MyTextBox.Text);
}
}
public class Book : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _title;
public string Title
{
get { return _title; }
set { _title = value; }
}
private double _price;
public double Price
{
get { return _price; }
set
{
if (value < 0)
{
throw new Exception("单价不能为负数!");
}
_price = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Price"));
}
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
public class Book : INotifyPropertyChanged{}