首先与Winforms和EF 4.1代码绑定
本文关键字:代码 绑定 EF Winforms | 更新日期: 2023-09-27 18:02:12
我想让Winforms组合框在新行写入数据库时自动刷新。
POCO EF class:
public class BaseSweep
{
public int BaseSweepId { get; set; }
//stuff removed for clarity
}
我通过BindingList像这样绑定到数据:
public BindingList<BaseSweep> TopSweeps()
{
LocalDbContext.BaseSweep.Load();
return LocalDbContext.BaseSweep.Local.ToBindingList();
}
private void BindSweepList() //called in Form_Load
{
comboBoxSweepIds.DataSource = _dataAccess.TopSweeps();
comboBoxSweepIds.DisplayMember = "BaseSweepId";
comboBoxSweepIds.ValueMember = "BaseSweepId";
}
这对于初始绑定很好,在表中显示当前id。随着新行添加到表中,LocalDbContext.BaseSweep.Local
中的计数如预期的那样增加。但是,comboBoxSweepIds
从不更新。你知道我做错了什么吗?
您需要在每次添加一行时触发一个事件并调用bind
Mark W引导我走正确的路:
//put an event handler on the collection
public void CollectionChanged<T>(System.Collections.Specialized.NotifyCollectionChangedEventHandler eventHandler) where T : class
{
LocalDbContext.Set<T>().Local.CollectionChanged += eventHandler;
}
在表单类(_sweepCollection
)中使用私有BindingList<T>
private void BindSweepList()
{
_sweepCollection = _dataAccess.TopSweeps();
_dataAccess.CollectionChanged<CableSweepDebug>(new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Local_CollectionChanged));
UpdateSweepsData();
}
private void Local_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
UpdateSweepsData();
}
private void UpdateSweepsData()
{
if (comboBoxSweepIds.InvokeRequired)
{
Invoke(new UpdateSweepCount(UpdateSweepsData));
}
else
{
var tmpBind = _sweepCollection.OrderByDescending(t => t.BaseSweepId).Take(100);
comboBoxSweepIds.DataSource = null;
comboBoxSweepIds.DataSource = tmpBind.ToList() ;
comboBoxSweepIds.DisplayMember = "BaseSweepId";
comboBoxSweepIds.ValueMember = "BaseSweepId";
}
}