的問題是,你正在編輯在這兩種形式相同的對象。您應該將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();