MVVM in WPF – Is Property Injection on a View Model Okay?

cdesign-patternsmvvmwpf

I am rather new to the concept of MVVM in C#/.NET WPF projects. The way I understand it, the view-model is supposed to lessen the amount of code-behind required to display data on a form. I try to do as much of the interaction logic as possible in the view-model, so any objects I will use get passed into the view-model via property injection. The view-model will then utilize those objects to do whatever the application is supposed to do.

The only logic I have in the view is to instantiate something based on a user selection and pass it immediately into the view-model. Additionally, I only really need to do that with a few things that don't make sense to bind (everything else uses data-binding).

What I am asking is… Is it generally okay to pass objects to the view-model? Or, does that create some kind of coupling or other problems I am not aware of?

Best Answer

What kind of objects do you want to pass to your ViewModel?

My view of MVVM is that my ViewModels are my application, and the View is just a pretty user-friendly interface for interacting with the ViewModels. In an ideal world, you should be able to easily hook up a command-line interface to your ApplicationViewModel and perform the same actions.

It sounds like you have the View creating an object based on a View's SelectedItem, and trying to pass the created object to a ViewModel. That's typically not what you want.

What you should have is a ViewModel containing a SelectedItem (which is bound to the View to give the user an easy way to change it), and that ViewModel should create your object using the ViewModel.SelectedItem property. From there, it can pass it to another ViewModel if needed, or take some other action on it.

I have a very simple MVVM example on my blog if you're interested in understanding the pattern a bit more. Its what I typically give to WPF beginners on StackOverflow who are looking for a basic example. :)

Related Topic