Using the MVVM pattern creating WPF applications you have the ViewModel providing data to the View. I’ve met a situation where I find it reasonable to create WPF objects in my ViewModel, and the View fetches these and shows them. More specifically I have functionality for drawing where I need to store an InkPresenter in the end. I receive the mouse gestures in the code-behind of the view, but pass the events to the ViewModel. The ViewModel handles the mouse event and creates drawing objects that is put in an ObservableCollection such that the View can fetch them out and display them.
The question is; is this okay, or is it bad practice to create WPF objects in the ViewModel classes? And why? If it is okay; are there any best practices or recommendations to dealing with these objects?
No, it’s “not okay” (quotations as I am talking about best practices – saying a ViewModel is no ViewModel because it does so is as wrong) to create and reference WPF (Control-)classes inside your ViewModels.
A very big disadvantages comes in when you try to unittest your ViewModel: The controls need special treatments and represent not-wanted dependencies.
You should only pass the actual “data” of those objects to the ViewModel: For the example with the InkPresenter it would be O.k. in my opinion to send the ViewModel the StylusPoints but not the InkPresenter itself. Even better would be ViewModel classes representing the StylusPoints – they could be mapped to the actual StylusPoints by databinding (I don’t know whether this is possible with the InkPresenter) or via some mediators (e.g. using attached properties).
For creation you can use some mediator, too, which you pass e.g. ViewModels and which then creates the suitable WPF-Control and sets the VM as its DataContext.