0
votes

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?

2

2 Answers

1
votes

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:

<Button Name="SurnameTextBox" Text="{Binding Surname,Mode=TwoWay}" />
<Button Name="MyButton" Command="{Binding MyRelayCommand}" Content="OK" />

View Model:

public class MyViewModel : INotifyPropertyChanged
{
    // (note, raise property changed on the setter
    public string Surname { get; set; }

    public ICommand MyRelayCommand { get; set; }

    public MyViewModel
    {
        // set the command callback here
        MyRelayCommand = new RelayCommand(OKCommandHandler); 
    }

    private void OKCommandHandler(object parameter)
    {
        // save the record here using Surname, etc
        // (note that you don't even need to use parameter, so you can just ignore it)
    }
}
1
votes

you dont need to pass data from form to viewmodel because your viewmodel has allready all data.

your viewmodel expose all data through properties to your view and you bind to it. look at dbaseman answer.