实例 -验证文本框单价为大于零的正数,失去焦点时执行。
Xaml:
<Grid x:Name="LayoutRoot"Background="{x:Null}" Width="400"Height="200">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinitionWidth="0.3*"/>
<ColumnDefinitionWidth="0.7*"/>
</Grid.ColumnDefinitions>
<sdk:Label Height="20" HorizontalAlignment="Left"Name="ProductLable" Content="ProductName:"
Width="90" />
<sdk:Label Grid.Row="1" Height="20"HorizontalAlignment="Left" Name="PriceLable"Content="Price:"
Width="90"/>
<TextBox Grid.Column="1" Height="23"HorizontalAlignment="Left"
Name="textBox1"Text="{Binding ProductName,Mode=
OneWay}"
Width="180" />
<TextBox Grid.Column="1" Grid.Row="1" Height="23"HorizontalAlignment="Left"
Name="textBox2"Text="{Binding Price,Mode=
TwoWay,NotifyOnValidationError=True,ValidatesOnExceptions=True}"BindingValidatiWidth="180" />
<Button Content="Change" Grid.Row="2"Grid.Column="1" Height="23"
Name="button1"Width="75" Click="button1_Click" />
</Grid>
cs:
public partial class DataBindingAndValidate :UserControl
{
Book book = new Book();
public DataBindingAndValidate()
{
InitializeComponent();
book.ProductName = "test product name";
book.Price = 12.0;
this.textBox1.DataContext = book;
this.textBox2.DataContext = book;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
book.Price = book.Price + 10.0;
}
private void textBox2_BindingValidationError(object sender,ValidationErrorEventArgs
e)
{
if (e.Action == ValidationErrorEventActi
on.Added)
{
this.textBox2.BorderBrush = new SolidColorBrush(Colors.Red);
}
else if (e.Action == ValidationErrorEventActi
on.Removed)
{
this.textBox2.BorderBrush = newSolidColorBrush(Colors.LightGray);
}
}
}
public class Book : INotifyPropertyChanged
{
public event PropertyChangedEventHand
ler PropertyChanged;
private void NotifyPropertyChange(string propertyName) {
if (PropertyChanged != null)
{
PropertyChanged(this, newPropertyChangedEventArgs
(propertyName));
}
}
private string productName;
public string ProductName
{
get { return productName; }
set { productName = value; }
}
private double price;
public double Price
{
get { return price; }
set
{
if (value <= 0) {
throw new Exception("请输入大于零的正数!");
}
price = value;
NotifyPropertyChange("Price");
}
}
}
Xaml:
cs: