2011-07-13 102 views
2

我試圖讓新的行寫入我們的數據庫時Winforms組合框自動刷新。用Winforms和EF 4.1進行數據綁定代碼優先

POCO EF類:

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永遠不會更新。任何想法我做錯了什麼?

回答

0

馬克W的LED我以正確的方式:

//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; 
} 

使用私人BindingList<T>形式類(_sweepCollection

在第一次數據綁定,成立了事件處理程序:

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";     

    } 
} 
0

您需要觸發一個事件並在每次添加行時調用綁定。