的问题是,你正在编辑在这两种形式相同的对象。您应该将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();