在C#中,數據綁定和數據校驗通常與Windows Forms或WPF應用程序一起使用
Person
類:public class Person : INotifyPropertyChanged, IDataErrorInfo
{
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
// 實現INotifyPropertyChanged接口
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
// 實現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
屬性:// 創建一個Person實例
Person person = new Person();
// 創建一個Binding對象,將TextBox的Text屬性綁定到Person的Name屬性
Binding binding = new Binding("Text", person, "Name");
binding.ValidatesOnDataErrors = true; // 啟用數據錯誤校驗
// 將Binding對象添加到TextBox的Bindings集合中
textBoxName.DataBindings.Add(binding);
Person
類的Name
屬性。同時,由于我們已經啟用了數據錯誤校驗,所以當用戶輸入無效數據時,將顯示一個錯誤提示。這就是在C#中使用數據綁定進行數據校驗的基本方法。請注意,這里的示例是針對Windows Forms應用程序的,但是在WPF應用程序中,數據綁定和數據校驗的實現方式會有所不同。