我正在做一个WPF应用程序。其中我使用数据网格,它被绑定到一个集合customerCollection。我使用MVVM
我有一个按钮来添加一个新客户,点击它会显示一个对话框。通过对话框,我保存数据到我的SQL服务器数据库。一切正常,但是当对话框关闭时(CloseAction();). 数据网格不更新。我该怎么办?当我返回到任何其他菜单项并单击customer时,Datagrid被更新,而我在构造函数和命令执行中调用相同的函数。附上图片供参考
public CustomerViewModel()
{
ShowNewCustomerWindowCommand = new ViewModelCommand(ExecuteShowNewCustomerWindowCommand);
SearchCustomerCommand = new ViewModelCommand(ExecuteSearchCustomerCommand);
GetData();
}
protected void GetData()
{
customer = new ObservableCollection<CustomerModel>();
customer = customerRepository.GetByAll();
customerCollection = CollectionViewSource.GetDefaultView(customer);
customerCollection.Filter = FilterByName;
customerCollection.Refresh();
RaiseProperChanged();
}
private void ExecuteShowNewCustomerWindowCommand(object obj)
{
var addNewCustomer = new AddNewCustomer();
addNewCustomer.ShowDialog();
}
private void ExecuteSaveCustomerCommand(object obj)
{
customerModel.FirstName = FirstName;
customerModel.LastName = LastName;
customerModel.Contact = Contact;
customerModel.Address = Address;
customerRepository.Add(customerModel);
CloseAction();
GetData();
}
我只是猜测,因为您没有发布任何xaml或属性。我假设你至少有一个公共属性CustomerCollection和你的数据网格绑定到它。我会将代码更改为以下内容:
public CustomerViewModel()
{
customer = new ObservableCollection<CustomerModel>();
customerCollection = CollectionViewSource.GetDefaultView(customer);
customerCollection.Filter = FilterByName;
ShowNewCustomerWindowCommand = new ViewModelCommand(ExecuteShowNewCustomerWindowCommand);
SearchCustomerCommand = new ViewModelCommand(ExecuteSearchCustomerCommand);
GetData();
}
public ICollectionView CustomerCollection {get; init;}
protected void GetData()
{
customer.Clear();
customer.AddRange(customerRepository.GetByAll());
customerCollection.Refresh();
}
private void ExecuteShowNewCustomerWindowCommand(object obj)
{
var addNewCustomer = new AddNewCustomer();
addNewCustomer.ShowDialog();
}
private void ExecuteSaveCustomerCommand(object obj)
{
customerModel.FirstName = FirstName;
customerModel.LastName = LastName;
customerModel.Contact = Contact;
customerModel.Address = Address;
customerRepository.Add(customerModel);
CloseAction();
GetData();
}
xaml
<DataGrid ItemsSource="{Binding CustomerCollection, Mode=OneWay}"
- init ObservableCollection and ICollectionView once in tor
- 使用.Clear()代替新实例
- 添加customerRepository.GetByAll()