Recently I’m developing my first project using MVVM concept (I use WPF). I’ve read many tutorials (ia. famous J.Smith’s one) about MVVM before I started writing a code. Everything I’ve read had been clear until I started to code…
The problem is simple: in View layer I have a form with TextBoxes. Let’s say a few TextBoxes, ie.: Name, Surname, Phone number. When user fills all of them and clicks OK-button, I want to add new person (with specified personal details) to my local Database (I use Entity Framework as a ORM).
To do this I need to write something like this:
<Button Name="MyButton" Command="MyRelayCommandWhichNeedsAllOfTheTextboxes" Content="OK" />
Using CommandParameter I can pass one object from View to ViewModel. There are many textboxes so it’s probably not a good idea.
From XAML I can assign to CommandParameter whole form which needs to be filled by user. But then, inside ViewModel, I need to know all textboxes’ names. The main assumption in MVVM is that all the layers (View, ViewModel and Model) have to be independent.
What’s the best solution? How can I pass input data from form to ViewModel?
I would suggest having the relay command as part of your View Model — that way, when the command gets triggered, you’ll have access to all the properties you need.
XAML:
View Model: