更新数据源时刷新Datagrid

时间:2013-01-09 23:19:11

标签: wpf sql-server-2008 wpfdatagrid observablecollection inotifypropertychanged

我有一个数据网格,显示一个绑定到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();
    }

1 个答案:

答案 0 :(得分: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));
    }
  }
}
相关问题