4

我有一個數據網格,顯示一個表,它綁定到一個DataSource,它不斷更改時間約束。 如何更新我的DataSource值時更新數據網格的內容。數據源更新時刷新Datagrid

P.S:我的DataSource表中的值由監控系統更新。它的表值會定期更新。

我應該在我的EF中添加我的Observable集合?

private IQueryable<MyTable> GetMyTablesQuery(TestDBEntities1 testDBEntities1) 
    { 
     // definition of a Query to retrieve the info from my DB 
     System.Data.Objects.ObjectQuery<EF_demo1.MyTable> myTablesQuery = testDBEntities1.MyTables; 
     // Returns an ObjectQuery. 
     return myTablesQuery ; 
    } 

    private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     // A New entity container is created that uses the object context 
     var testDBEntities1 = new EF_demo1.HMDBEntities1(); 
     // Load data into MyTables. 
     var myTablesViewSource= ((System.Windows.Data.CollectionViewSource)(this.FindResource("myTablesViewSource"))); 
     // the query which is defined above is executed here. It grabs all the information from the entity container 
     IQueryable<EF_demo1.MyTable> myTablesQuery = this.GetMyTablesQuery(testDBEntities1); 
     //The query result is binded to the source of the myTablesViewSource, which inturn binds back to the list. 
     myTablesViewSource.Source = myTablesQuery .ToList(); 
    } 
+1

將綁定集合設置爲ObservableCollection並刪除/添加新值或對綁定集合使用INotifyPropertyChange。 –

+0

我已經使用連接字符串連接到數據庫,我正在填充我的datagrid.ItemSource到我的數據集。我沒有使用ObservableCollection填充Itemsource。所以,現在我必須改變數據檢索的方式,例如:使用EF? –

回答

3

一種可能的方法是使用一個ObservableCollection:

BoundCollection = new ObservableCollection<MyEntityType>(entities); 

BoundCollection在綁定使用。然後,每當值被更新時,你會清楚的收集和重新添加他們:

BoundCollection.Clear(); 
foreach(var e in entities) 
{ 
    BoundCollection.Add(e); 
} 

下面是一個使用INotifyPropertyChanged的每一次重新綁定收集另一種選擇。但是,使用ObservableCollection是首選方法,因爲它是爲添加和刪除將自動更新UI的項目而設計的。

public class MyModel : INotifyPropertyChanged 
{ 
    public IList<MyEntity> BoundCollection {get; private set;} 

    public MyModel() 
    { 
    UpdateBinding(); 
    } 

    private void UpdateBinding() 
    { 
    // get entities 
    BoundCollection = new List<MyEntity>(entities); 
    // this notifies the bound grid that the binding has changed 
    // and should refresh the data 
    NotifyPropertyChanged("UpdateBinding"); 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    private void NotifyPropertyChanged(string propertyName = "") 
    { 
    if (PropertyChanged != null) 
    { 
     PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 
    } 
} 
+0

我可以使用這個ObservableCollection,當我用Entity Framework綁定到我的數據庫吧?謝謝 ! –

+0

請參閱我的更新,它也提供了一種替代方法。 –

+0

非常感謝,我會嘗試這種方法,讓你知道:) –