namespace WindowsFormsApplication1
{
public partial class Myform : Form
{
public Myform()
{
InitializeComponent();
Initial();
}
public UiBindList<OBJ> _list { get; set; }
private void Initial()
{
_list = new UiBindList<OBJ> { SynchronizationContexts = SynchronizationContext.Current };
dataGridView1.DataBindings.Add("DataSource", this, "_list", false, DataSourceUpdateMode.OnPropertyChanged);
new Thread(() =>
{
while (true)
{
Thread.Sleep(1000);
_list.Add(new OBJ { Name = "C#" });
}
})
{
IsBackground = true,
}
.Start();
}
}
public class UiBindList<T> : BindingList<T>
{
public SynchronizationContext SynchronizationContexts { get; set; }
public void Excute(Action action, object state = null)
{
if (SynchronizationContexts == null)
action();
else
SynchronizationContexts.Post(p => action(), state);
}
public new void Add(T item)
{
Excute(() => base.Add(item));
}
public new void Remove(T item)
{
Excute(() => base.Remove(item));
}
}
public class OBJ { public string Name { get; set; } }
在Add方式中 报错!!对象的当前状态使该操作无效。