如何在C#中使用數(shù)據(jù)綁定進(jìn)行數(shù)據(jù)校驗(yàn)

c#
小樊
83
2024-08-30 23:19:31

在C#中,數(shù)據(jù)綁定和數(shù)據(jù)校驗(yàn)通常與Windows Forms或WPF應(yīng)用程序一起使用

  1. 創(chuàng)建一個(gè)數(shù)據(jù)模型類,該類將表示要綁定的數(shù)據(jù)。在這個(gè)例子中,我們將創(chuàng)建一個(gè)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;
        }
    }
}
  1. 在你的窗體或控件上創(chuàng)建一個(gè)文本框(TextBox),并將其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);
  1. 當(dāng)用戶輸入數(shù)據(jù)時(shí),數(shù)據(jù)綁定會(huì)自動(dòng)將數(shù)據(jù)傳遞給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ì)有所不同。

0