views:

35

answers:

1

i am developing an application in wpf using MVVM design pattern. i have a listbox when an item is slected then a dialog is open having the same record in editable mode. this dialog is binded with the selected item of the list. i have apply the validation rule for textbox using IDataErrorInfo. when the user update a record on dialogbox then at every key press, the selected record in listbox is also changed. if the user press save button then i submit changes to database. but if user click cancel button then i do not submit changes to database but the list box is updated with the current updation in GUI. when i refresh the list then old value appears again. My requirement is to update the listbox only when the user hit the save button but not on every key press on dialog box. I first fill the generic list with the linq to sql classes then bind the listbox with it. Please let me know what i have to do.

Thanks in advance

A: 

The problem is that you are editing the same object on both forms. You should pass the SelectedItem to the dialog form, but then re-query the database for the item that was passed to the constructor. This does two things: allows you to cancel the changes when the object has been edited, and provides the user with the most current data from the database.

Think of it this way... If the listbox contained data that was even a few minutes old, your user would be modifying data that may have already changed by another user running your application.

Once the user saves (or deletes) the record in the dialog form, you must then refresh the listbox. Typically I use the following method:

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);

ListBox ViewModel

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();
Brent