DataGridView解決使用BindingList時屬性改變界面不更新問題

 

      在使用BindingList作爲DataGridView的數據源時,當BindingList<>有增加或者刪除的時候DataGridView會自動刷新,但是當BindingList<>中屬性內容進行更新的時候界面並不會刷新,是因爲實體類沒有實現INotifyPropertyChanged接口,實現相關接口即可。

代碼如下:

  public class ValueList : INotifyPropertyChanged
    {

        private string _Value;
        private int _Index;
    

        public string Value
        {
            get { return _Value; }
            set
            {
                if (value != _Value)
                {
                    _Value = value;
                    NotifyPropertyChanged();
                }
            }
        }
        public int Index
        {
            get { return _Index; }
            set
            {
                if (value != _Index)
                {
                    _Index = value;
                    NotifyPropertyChanged();
                }

            }
        }

        public ValueList(string Value, int Index)
        {
            this.Value = Value;
            this.Index = Index;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

測試如下:

 DataSource = new BindingList<ValueList>();
 DataSource.Add(new ValueList("abcd", 1));
 DataSource.Add(new ValueList("1234", 1));
 DataSource.Add(new ValueList("2345", 2));
 DataSource.Add(new ValueList("3456", 3));
 DataGridView.DataSource = DataSource;

private void TestButton_Click(object sender, EventArgs e)
{
    // DataSource.Add(new ValueList("DDDD", 6));
    DataSource[0].Value = "EFEF";
    DataSource[0].Index = 2;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章