【问题标题】:Refresh Datagrid when Datasource is updated更新数据源时刷新数据网格
【发布时间】:2026-02-08 12:55:02
【问题描述】:

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

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();
    }

【问题讨论】:

  • 要么将绑定集合设置为 ObservableCollection 并删除/添加新值,要么在绑定集合上使用 INotifyPropertyChange。
  • 我已经使用连接字符串连接到数据库,我正在将我的 datagrid.ItemSource 填充到我的数据集。我没有使用 ObservableCollection 来填充 Itemsource。那么,现在我是否必须改变数据检索的方式,例如:使用 EF ?

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


【解决方案1】:

一种可能的方法是使用 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));
    }
  }
}

【讨论】:

  • 当我使用实体框架绑定到我的数据库时,我可以使用这个 ObservableCollection 吗?谢谢!
  • 非常感谢,我会尝试这种方法并告诉你:)
  • 我在上面添加了我的 EF 数据绑定。您能否告诉我应该在哪里插入 ObservableCollection 或 INotifyPropertyChanged 以通过它们实现数据绑定?谢谢
  • 发布您用于绑定到网格的属性,即用作ItemsSource 的属性。 myTablesViewSource 是什么?
  • 您需要将列表更改为 ObservableCollection,然后删除/添加项目,如答案所示。不要每次都重新初始化列表,只需清除并添加新项目即可。