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

非常感谢,我会尝试这种方法,让你知道:) –