【问题标题】:How to make WPF DataGrid display up-to-date content?如何让 WPF DataGrid 显示最新的内容?
【发布时间】:2012-11-10 13:40:10
【问题描述】:
现在我有一个 WPF DataGrid,它显示从 LINQ to Entity 查询获得的列表。然而,这并不意味着如果我从数据库中删除某些内容,它将立即从DataGrid 中删除。我试过myGrid.Items.Refresh(),但它只刷新了一个单元格。
我知道ObservableCollection 可以以某种方式解决问题,但我不知道在哪里创建这样的集合和适当的方法,以便每当我创建/添加/修改数据库时,集合也会被修改。
【问题讨论】:
标签:
wpf
database
binding
datagrid
【解决方案2】:
您不需要通过代码与 DataGrid 进行交互。相反,将 DataGrid 的 ItemsSource 绑定到 ObservableCollection 并操作集合。 DataGrid 将自动更新。
看这里:Bind ObservableCollection to a DataGrid after assigning new value
事实上,您会意识到在很多情况下(在我的情况下,这是 95% 的情况),您不想为 WPF 控件命名。如果您的代码不了解您的 UI,从长远来看更容易维护。让您的 UI 知道通过数据绑定从何处获取其信息。并查看 INotifyPropertyChanged 或 Dependency Properties 和 DataContext。
<DataGrid ItemsSource="{Binding MyCollection}" />
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
ObservableCollection<object> myCollection = new ObservableCollection<object>();
public ObservableCollection<object> MyCollection
{
get
{
return myCollection;
}
set
{
myCollection = value;
// Call the Notification here. Using linq and reflection you could get it to look like this:
// NotifyPropertyChanged(() => MyCollection);
}
}
如果您实际上并未更改 myCollection 值,则无需提供更改通知。当您修改集合时,ObservableCollection 实际上会提供自己的更改。