2010-06-13 128 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();