2010-06-13 114 views
1

我正在使用MVVM設計模式在wpf中開發應用程序。當一個項目被選中時,我有一個列表框,然後在可編輯模式下打開一個具有相同記錄的對話框。該對話框與列表中的選定項目綁定。我已經使用IDataErrorInfo應用了文本框的驗證規則。當用戶更新對話框上的記錄時,在每次按鍵時,列表框中的選定記錄也會更改。如果用戶按保存按鈕,然後我提交更改數據庫。但如果用戶單擊取消按鈕,那麼我不會提交對數據庫的更改,但列表框會使用GUI中的當前更新進行更新。當我刷新列表時,舊值再次出現。我的要求是僅在用戶點擊保存按鈕時才更新列表框,而不是在每次按下對話框時按下。我首先用linq to sql類填充通用列表,然後用它綁定列表框。請讓我知道我必須做什麼。WPF中的輸入驗證

在此先感謝

回答

0

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