我将一个ObservableCollection CustomerList绑定到一个数据网格,它在最初打开时工作正常,但是当我使用一个按钮来调用函数来向CustomerList提供一个新对象时,数据网格没有刷新,我知道这是数据网格更新的工作方式,因为原始的CustomerList没有更新,所以在这种情况下我该怎么做才能解决问题?我正在使用MVVM模式
class CustomerViewModel
{
public ObservableCollection<Customer> CustomerList { get; set; }
public RelayCommand SearchCommand { get; set; }
public CustomerViewModel()
{
CustomerList = new ObservableCollection<Customer>(customerDAL.GetAllCustomers());
SearchCommand = new RelayCommand(SearchCustomersByKeyWords);
}
void SearchCustomersByKeyWords(object parameter)
{
CustomerList = new ObservableCollection<Customer>(customerDAL.SearchByKeywords(keyWords));
}
}
答案 0 :(得分:3)
CustomerViewModel
实际上不是一个视图模型。它只是一个普通的课程。要成为正确的视图模型,需要implement INotifyPropertyChanged
。
当您更改CustomerList
的值时,您必须提升PropertyChanged
事件INotifyPropertyChanged
。否则,UI永远不会知道CustomerList
的值已更改。 DataGrid.ItemsSource
上的绑定不知道您更新了源属性,因此它不会更新目标属性。
CustomerList
应该是这样的:
public class CustomerViewModel : ViewModelBase
{
private ObservableCollection<Customer> _customerList = new ObservableCollection<Customer>();
public ObservableCollection<Customer> CustomerList {
get { return _customerList; }
set {
if (_customerList != value) {
_customerList != value;
// Member of ViewModelBase that raises PropertyChanged
OnPropertyChanged(nameof(CustomerList));
}
}
}
编写一个实现ViewModelBase
的{{1}}类;你会在网上找到很多这方面的例子。
一个糟糕的解决方法是保留你收集的集合,但是INotifyPropertyChanged
它并在循环中逐个添加新项目。