更新数据源时刷新数据网格



我有一个数据网格,显示一个表,该表绑定到一个在时间限制下不断变化的DataSource。当我的DataSource值更新时,如何刷新数据网格的内容。

p。S:我的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.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));
    }
  }
}

相关内容

  • 没有找到相关文章

最新更新