I’m starting to learn MVVM and have seen how to bind the data list with the corresponding List<> in ViewModel. Now I need to realize a form that has different fields and, when the user clicks a button, I have to save data to a local database.
Which is the "most-MVVM" approach? I think to implement a SaveItem(Item){} method in ViewModel and, in code behind, for button click do something like
Item item = new Item();
item.field1 = txt1.Text;
...
item.fieldn = txtn.Text;
myViewModel.SaveItem(item);
I think there must be a cleaner way.
A
Buttonhas aDependencyPropertyof typeICommandcalledCommandProperty, and if that property is set the command will be invoked when theButtonis clicked.Typically in MVVM, one exposes a property of type
ICommand(you need to create an implementation or take one from a framework) and binds to it in XAML like so:view-model:
Now you have no need for code-behind.
As for getting at the text that you want to save, again you want to favor databinding to your view-model rather than code-behind.
Instead of reading
TextBox.Text, bind that property to your view-model.view-model:
xaml:
Notice that we are using the
TwoWaybinding mode. That way changes in the viewmodel can be reflected in theTextBox(that’s why you need to implementINotifyPropertyChanged), and changes in theTextBoxwill be propagated to the view-model.I also added the
UpdateSourceTriggersetting because by default the view-model would only be updated when theTextBoxloses focus. This way the view-model gets updated whenever the value changes. Use whatever makes sense in your application.