用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起來。我們在年齡上選一條記錄,進入編輯狀態後,輸入字母(應為整數),然後試著確認,看看發生了什麼事?
在日期處也試試。