IEditableObject and Restoring Text After Cancelling Changes

Standard

It’s a common scenario, the user starts to edit something and then changes their mind. What happens in an application with Two-Way binding? As soon as the user began to type you began persisting the data, in effect there is no going back.

Cue IEditableObject to the rescue!

The answer is to implement the IEditableObject interface on your class. The interface defines 3 void methods: BeginEdit(), CancelEdit(), & EndEdit().

In the BeginEdit() we set the editing mode to true and make a copy of the original value. If you were dealing with more than one field, I recommend getting a copy of your object using MemberwiseClone, unless your class includes reference types in which case you will want to make a deep copy instead.

public void BeginEdit()
{
     IsEditing = true;
     // Save a copy of the original value
     originalmessage = this.Messages;
}

public void CancelEdit()
{
      // Put the original value back
      this.Messages = originalmessage;
      IsEditing = false;
}

public void EndEdit()
{
      IsEditing = false;
      // Save the current value of the field
      repository.SaveMessages(this.Messages); 
}