用DataGrid进行数据验证,一句话:太简单了,为什么?因为它自身已经具备了很完善的数据验证功能。
好,说多无益,最好的办法,来,写个例子试试。
老规矩,先准备点数据来测试,既然要数据验证,就不能全弄字符串的,弄点整型的,日期型的,这样就有利于演示。
public class Employee { public string Name { get; set; } public int Age { get; set; } public DateTime Birthday { get; set; } }
该类声明三个属性,分别是字符串,整型,日期型。
好,我们来看看DataGrid默认的验证功能。
要进行验证只需做好以下工作:
把Binding的ValidatesOnExceptions设为True,NotifyOnValidationError设为true,UpdateSourceTrigger设置为Explicit。
好,看XAML:
<UserControl x:Class="DataValidationSample.MainPage" 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:DesignWidth="640" d:DesignHeight="480" xmlns:sdk="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"> <Grid x:Name="LayoutRoot"> <sdk:DataGrid x:Name="Grid" CanUserReorderColumns="True" CanUserSortColumns="True" AutoGenerateColumns="False"> <sdk:DataGrid.Columns> <!--声明列,并进行绑定--> <sdk:DataGridTextColumn Header="姓名" Width="auto"> <sdk:DataGridTextColumn.Binding> <Binding Path="Name" Mode="TwoWay" UpdateSourceTrigger="Explicit" ValidatesOnExceptions="True" NotifyOnValidationError="True"/> </sdk:DataGridTextColumn.Binding> </sdk:DataGridTextColumn> <sdk:DataGridTextColumn Header="年龄" Width="auto"> <sdk:DataGridTextColumn.Binding> <Binding Path="Age" Mode="TwoWay" ValidatesOnExceptions="True" NotifyOnValidationError="True" UpdateSourceTrigger="Explicit"/> </sdk:DataGridTextColumn.Binding> </sdk:DataGridTextColumn> <sdk:DataGridTextColumn Header="生日" Width="auto"> <sdk:DataGridTextColumn.Binding> <Binding Path="Birthday" Mode="TwoWay" ValidatesOnExceptions="True" NotifyOnValidationError="True" UpdateSourceTrigger="Explicit"/> </sdk:DataGridTextColumn.Binding> </sdk:DataGridTextColumn> </sdk:DataGrid.Columns> </sdk:DataGrid> </Grid> </UserControl>
最后,在类用户控制的构造函数中设置数据源。
public partial class MainPage : UserControl { ObservableCollection<Employee> Employs = null; public MainPage() { InitializeComponent(); this.Employs = new ObservableCollection<Employee>(); Employs.Add(new Employee { Name = "李小同", Age = 27, Birthday = new DateTime(1988, 12, 10) }); Employs.Add(new Employee { Name = "南郭先生", Age = 43, Birthday = new DateTime(1976, 3, 12) }); Employs.Add(new Employee { Name = "汤老头", Age = 36, Birthday = new DateTime(1978, 5, 1) }); Employs.Add(new Employee { Name = "林大吉", Age = 28, Birthday = new DateTime(1987, 6, 21) }); //绑定 this.Grid.ItemsSource = Employs; } }
好了,请申出你的手指头,轻轻地按一下F5,把程序Run起来。
我们在年龄上选一条记录,进入编辑状态后,输入字母(应为整数),然后试着确认,看看发生了什么事?
在日期处也试试。