[英]Refresh Datagrid when Datasource is updated
我有一個數據網格,顯示一個綁定到DataSource
的表,該DataSource
不斷更改時間約束。 如何在更新DataSource
值時刷新數據網格的內容。
PS:我的DataSource
表中的值由監控系統更新。 其表值定期更新。
我應該在EF中添加我的Observable Collection?
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();
}
一種可能的方法是使用ObservableCollection:
BoundCollection = new ObservableCollection<MyEntityType>(entities);
BoundCollection
中使用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));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.