WPF,数据验证
class Person
{
private int age;
public int Age
{
get { return age; }
set
{
if (value < 42)
throw new Exception("年龄太小");
else
age = value;
}
}
}
<Grid HorizontalAlignment="Left" Height="372" VerticalAlignment="Top" Width="467">
<Grid.Resources>
<local:Person x:Key="person1"></local:Person>
</Grid.Resources>
<TextBox HorizontalAlignment="Left" Height="23" Margin="87,173,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120">
<TextBox.Text>
<Binding Source="{StaticResource person1}" Path="Age" ValidatesOnExceptions ="True"/>
</TextBox.Text>
</TextBox>
</Grid>
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
Title="" Height="400" Width="550" >
<StackPanel>
<StackPanel.Resources>
<local:Person x:Key="person1"></local:Person>
</StackPanel.Resources>
<TextBox>
<TextBox.Text>
<Binding Source="{StaticResource person1}" Path="Age" ValidatesOnExceptions ="True"/>
</TextBox.Text>
</TextBox>
<TextBox></TextBox>
</StackPanel>
</Window>
using System;
using System.Windows;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
class Person
{
private int age;
public int Age
{
get { return age; }
set
{
if (value < 42)
throw new Exception("年龄太小");
else
age = value;
}
}
}
}