在使用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;
}