Here is the situation: I have an editor app, that edits some hierarchical data. The data itself is held in ViewModel class, and View class is responsible to reflect changes in ViewModel. The main part of the View is ContentControl. When data changes in ViewModel, a hierarchical structure of controls is (re)generated and top-level control becomes the Content of the ContentControl. Of course, those hierarchical controls have bindings. Now it's time to close the editor. ViewModel reacts to command and clears the data. PropertyChanged is raised and the View is ready to react: it attempts to do
myContentControl.Content = null;
But this is where the pitfall is: WPF detaches hieararchy of controls from ContentControl's visual tree and re-evaluates bindings. But the data is already destroyed!
What should I do? Why WPF updates bindings on controls that go out of visual tree? Of course I can do additional check for nulls, but is there a way not to do binding at all on half-dead controls?
Whenever we have a UI that enables a user to edit an object, but also provides the possibility of saving or cancelling, we simply need to use another view model class for that view.
Therefore, when editing starts you copy the fields from the current object to the editable properties in the view model. We then leave the user to edit what they want. If they cancel the operation, then we do nothing, as the original object is untouched.
However, if they want to save, then we copy the properties from the edited view model to the original object and save it. Then the view and view model can be disposed of without consequence.