我有MainWindow和Window Add,ViewModel和ViewModelADD..l'添加新客户在数据库中是正确的,但DataGrid的刷新没有!当我完成l'时,Window ADD不会关闭!
视图模型:
private static ViewModel1 instance = new ViewModel1();
public static ViewModel1 Instance { get { return instance; } }
private void add(object obj)
{
Add addView = new Add();
addView.DataContext = new ViewModelADD(loadDataBinding);
addView.Show();
}
private ObservableCollection<Custmor> _loadDataBinding;
public ObservableCollection<Custmor> loadDataBinding
{
get
{
return _loadDataBinding;
}
set
{
_loadDataBinding = value;
OnPropertyChanged("loadDataBinding");
}
}
ViewModelADD:
public ViewModelADD(ObservableCollection<Custmor> loadDataBinding)
{
CustomerToAddObject = new Custmor();
addCustomer1 = new RelayCommand(ADDFunction);
}
private ICommand addCustomer1;
public ICommand AddCustomer1
{
get { return addCustomer1; }
}
private void ADDFunction(object obj)
{
using (Test1Entities context = new Test1Entities())
{
context.Custmor.Add(customerToAddObject);
context.SaveChanges();
}
ViewModel1.Instance.loadDataBinding.Add(customerToAddObject);
if (addView != null)
addView.Close();
CustomerToAddObject = new Custmor();
我尝试使用以下命令刷新DataGrid:
ViewModel1.Instance.loadDataBinding.Add(customerToAddObject);
并尝试关闭Window ADD,我尝试:
if (addView != null)
addView.Close();
CustomerToAddObject = new Custmor();
但问题仍然存在:dataGrid没有刷新,Window ADD没有关闭..数据库中的保存是正确的
答案 0 :(得分:1)
将对象添加到注入ViewModelADD
的集合中:
private readonly ObservableCollection<Custmor> _loadDataBinding;
public ViewModelADD(ObservableCollection<Custmor> loadDataBinding)
{
CustomerToAddObject = new Custmor();
addCustomer1 = new RelayCommand(ADDFunction);
_loadDataBinding = loadDataBinding;
}
...
private void ADDFunction(object obj)
{
using (Test1Entities context = new Test1Entities())
{
context.Custmor.Add(customerToAddObject);
context.SaveChanges();
}
_loadDataBinding.Add(customerToAddObject);
...
}
由于您从视图模型中打开窗口,您也可以注入窗口:
private readonly Window _window;
private readonly ObservableCollection<Custmor> _loadDataBinding;
public ViewModelADD(Window window, ObservableCollection<Custmor> loadDataBinding)
{
CustomerToAddObject = new Custmor();
addCustomer1 = new RelayCommand(ADDFunction);
_window = window;
_loadDataBinding = loadDataBinding;
}
...
private void ADDFunction(object obj)
{
using (Test1Entities context = new Test1Entities())
{
context.Custmor.Add(customerToAddObject);
context.SaveChanges();
}
_loadDataBinding.Add(customerToAddObject);
_window.Close();
...
}