在使用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;
}
本文探讨了在使用BindingList作为DataGridView数据源时,如何实现实时更新的问题。当BindingList的内容发生变化,如属性更新,界面不会自动刷新。解决办法是使实体类实现INotifyPropertyChanged接口,确保属性变化时通知DataGridView,从而实现界面的实时更新。

485

被折叠的 条评论
为什么被折叠?



