DataGridView解決使用BindingList時屬性改變介面不更新問題
阿新 • • 發佈:2018-12-16
在使用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; }