Reputation: 461
I have a data grid that displays a Table which is bound to a DataSource
which keeps changing on a time constraint.
How to refresh the data grid's content when myDataSource
values are updated.
P.S : The values in my DataSource
Tables are updated by a monitoring system. Its table values are updated in regular intervals.
Where should I add my Observable Collection in my EF ?
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();
}
Upvotes: 4
Views: 3007
Reputation: 38335
One possible way is to use an ObservableCollection:
BoundCollection = new ObservableCollection<MyEntityType>(entities);
Where BoundCollection
is used in your binding. And then whenever the values are updated, you would clear the collection and re-add them:
BoundCollection.Clear();
foreach(var e in entities)
{
BoundCollection.Add(e);
}
Here's another option that uses INotifyPropertyChanged and rebinds the collection each time. However, using an ObservableCollection is the preferred method as its is designed for adding and removing items which will automatically update the 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));
}
}
}
Upvotes: 3