问题是您在两个表单上编辑同一个对象。您应该将 SelectedItem 传递给对话框表单,然后重新查询数据库以获取传递给构造函数的项目。这有两件事:允许您在编辑对象时取消更改,并为用户提供数据库中的最新数据。
这样想...如果列表框包含的数据甚至是几分钟前的数据,那么您的用户将修改可能已经被另一个运行您的应用程序的用户更改的数据。
一旦用户在对话框表单中保存(或删除)记录,您就必须刷新列表框。通常我使用以下方法:
DialogViewModel:
// Constructor
public DialogViewModel(MyObject myObject)
{
// Query the database for the required object
MyObject = (from t in _dc.MyObjects where t.ID == myObject.ID
select t).Take(1).Single();
}
// First define the Saved Event in the Dialog form's ViewModel:
public event EventHandler Saved;
public event EventHandler RequestClose;
// Raise the Saved handler when the user saves the record
// (This will go in the SaveCommand_Executed() method)
EventHandler saved = this.Saved;
if (saved != null)
saved(this, EventArgs.Empty);
列表框视图模型
Views.DialogView view = new Views.DialogView();
DialogViewModel vm = new DialogViewModel(SelectedItem); // Pass in the selected item
// Once the Saved event has fired, refresh the
// list of items (ICollectionView, ObservableCollection, etc.)
// that your ListBox is bound to
vm.Saved += (s, e) => RefreshCommand_Executed();
vm.RequestClose += (s, e) => view.Close();
view.DataContext = vm;
view.ShowDialog();