コントロールがデータソースに連結されている場合、データを表すエンティティ クラスのプロパティに検証処理を実装する方法があります。
次のサンプルコードは Employee クラスの ID プロパティに文字数の検証を実装します。なお、コントロールをデータソースに連結する方法について詳しくは「データ連結の基本 」を参照してください。
XAML |
コードのコピー |
---|---|
<sg:GcSpreadGrid ItemsSource="{StaticResource EmployeeCollection}"/> |
C# |
コードのコピー |
---|---|
public class Employee : INotifyPropertyChanged { string id; string name; DateTime hiredate; DateTime birthday; public string ID { set { if (value.Length > 9) throw new Exception("IDが10文字以上で長過ぎます。"); id = value; NotifyPropertyChanged("ID"); } get { return id; } } [Display(ShortName="氏名")] public string Name { set { name = value; NotifyPropertyChanged("Name"); } get { return name; } } [Display(ShortName = "入社日")] public DateTime HireDate { set { hiredate = value; NotifyPropertyChanged("HireDate"); } get { return hiredate; } } [Display(ShortName = "誕生日")] public DateTime Birthday { set { birthday = value; NotifyPropertyChanged("Birthday"); } get { return birthday; } } public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public class EmployeeCollection : ObservableCollection<Employee> { public EmployeeCollection() { Add(new Employee() { ID = "U10200115", Name = "福山 敏道", HireDate = DateTime.Parse("2003/12/1"), Birthday=DateTime.Parse("1977/9/17")}); } } |
Visual Basic |
コードのコピー |
---|---|
Public Class Employee Implements INotifyPropertyChanged Private m_id As String Private m_name As String Private m_hiredate As DateTime Private m_birthday As DateTime Public Property ID() As String Get Return m_id End Get Set(value As String) If value.Length > 9 Then Throw New Exception("IDが10文字以上で長過ぎます。") End If m_id = value NotifyPropertyChanged("ID") End Set End Property <Display(ShortName:="氏名")> _ Public Property Name() As String Get Return m_name End Get Set(value As String) m_name = value NotifyPropertyChanged("Name") End Set End Property <Display(ShortName:="入社日")> _ Public Property HireDate() As DateTime Get Return m_hiredate End Get Set(value As DateTime) m_hiredate = value NotifyPropertyChanged("HireDate") End Set End Property <Display(ShortName:="誕生日")> _ Public Property Birthday() As DateTime Get Return m_birthday End Get Set(value As DateTime) m_birthday = value NotifyPropertyChanged("Birthday") End Set End Property Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged Protected Sub NotifyPropertyChanged(propertyName As String) RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) End Sub End Class Public Class EmployeeCollection Inherits ObservableCollection(Of Employee) Public Sub New() Add(New Employee() With {.ID = "U10200115", .Name = "福山 敏道", _ .HireDate = DateTime.Parse("2003/12/1"), .Birthday = DateTime.Parse("1977/9/17")}) End Sub End Class |