- <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起来。
我们在年龄上选一条记录,进入编辑状态后,输入字母(应为整数),然后试着确认,看看发生了什么事?
在日期处也试试。