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