在C#中,數(shù)據(jù)綁定和數(shù)據(jù)校驗(yàn)通常與Windows Forms或WPF應(yīng)用程序一起使用
Person
類:public class Person : INotifyPropertyChanged, IDataErrorInfo
{
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
// 實(shí)現(xiàn)INotifyPropertyChanged接口
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
// 實(shí)現(xiàn)IDataErrorInfo接口
public string Error => null;
public string this[string columnName]
{
get
{
string result = null;
if (columnName == "Name")
{
if (string.IsNullOrEmpty(_name))
result = "Name cannot be empty";
else if (_name.Length < 3)
result = "Name must be at least 3 characters long";
}
return result;
}
}
}
Text
屬性綁定到Person
類的Name
屬性:// 創(chuàng)建一個(gè)Person實(shí)例
Person person = new Person();
// 創(chuàng)建一個(gè)Binding對(duì)象,將TextBox的Text屬性綁定到Person的Name屬性
Binding binding = new Binding("Text", person, "Name");
binding.ValidatesOnDataErrors = true; // 啟用數(shù)據(jù)錯(cuò)誤校驗(yàn)
// 將Binding對(duì)象添加到TextBox的Bindings集合中
textBoxName.DataBindings.Add(binding);
Person
類的Name
屬性。同時(shí),由于我們已經(jīng)啟用了數(shù)據(jù)錯(cuò)誤校驗(yàn),所以當(dāng)用戶輸入無(wú)效數(shù)據(jù)時(shí),將顯示一個(gè)錯(cuò)誤提示。這就是在C#中使用數(shù)據(jù)綁定進(jìn)行數(shù)據(jù)校驗(yàn)的基本方法。請(qǐng)注意,這里的示例是針對(duì)Windows Forms應(yīng)用程序的,但是在WPF應(yīng)用程序中,數(shù)據(jù)綁定和數(shù)據(jù)校驗(yàn)的實(shí)現(xiàn)方式會(huì)有所不同。