这是我的问题:我有一个绑定到自定义对象的 BindingList 的 DataGridView。后台线程不断更新这些对象的值。udpates 显示正确,一切都很好,除了一件事 - 如果您在更新背景更新字段时尝试编辑不同的字段,它会丢失输入的值。这是一个演示此行为的代码示例:(对于新表单,请在其上放置一个新的 DataGridView:)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private BindingList<foo> flist;
private Thread thrd;
private BindingSource b;
public Form1()
{
InitializeComponent();
flist = new BindingList<foo>
{
new foo(){a =1,b = 1, c=1},
new foo(){a =1,b = 1, c=1},
new foo(){a =1,b = 1, c=1},
new foo(){a =1,b = 1, c=1}
};
b = new BindingSource();
b.DataSource = flist;
dataGridView1.DataSource = b;
thrd = new Thread(new ThreadStart(updPRoc));
thrd.Start();
}
private void upd()
{
flist.ToList().ForEach(f=>f.c++);
}
private void updPRoc()
{
while (true)
{
this.BeginInvoke(new MethodInvoker(upd));
Thread.Sleep(1000);
}
}
}
public class foo:INotifyPropertyChanged
{
private int _c;
public int a { get; set; }
public int b { get; set; }
public int c
{
get {return _c;}
set
{
_c = value;
if (PropertyChanged!= null)
PropertyChanged(this,new PropertyChangedEventArgs("c"));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
}
因此,您编辑列 a 或 b,您将看到列 c 更新导致您丢失条目。
任何想法表示赞赏。