c# – What is the proper way to handle with View and ViewModel in WPF?


Currently, I’m making an Editor with MVVM pattern in WPF. Editor simply take an instance of a specific type as a reference and modifies it. The following code is the expected usage when editor development is completed.

MyEditor myEditor = new MyEditor();
myEditor.Show();
myEditor.Edit(myDataInstance1); // Bind myDataInstance1 to the editor and edit it.
myEditor.Edit(myDataInstance2);
myEditor.Clear();
myEditor.Close();
... and so on ...

So, I first divided the program into Model, ViewModel, and View. But, one question arose here. Where should I declare the Show(), Edit(), Clear(), Close() methods? And how should each View and ViewModel class be handled? I thought about it like this, but I didn’t come up with a good alternative.

  • In the View constructor, set ViewModel to DataContext, create an instance of View, and access the DataContext of View and call the ViewModel method…
  • Directly access to the ViewModel methods. (View and ViewModel must be managed separately)
  • Create an independent class called MyEditor to manage View and ViewModel, and connect ViewModel’s methods and MyEditor’s methods. Users use the method of MyEditor.

Of the methods I thought, the third method is the most likely, but I’m not sure. The composition of the editor is not very simple. Basically, the Editor is largely composed of View, ViewModel, and Model, but inside the ViewModel, i must also handle with sub views for various MyChildTypes that can be edited. (There are several MyChildType classes that inherit MyBaseType class, and each MyChildType has its own editable View.) So, if I pass an instance of MyChildType to the Editor, the Editor should show an editable view suitable for that type. Type check and sub view replacement itself is easy, but, I don’t know a proper way to set the MyChildType instance to the editor. Please advise me.