MVVM in VB.Net - Lesson 5: The ViewModel
ViewModels can alter data heading back to the model, and/or it could expose the model to the view. We will create a ViewModel where it will expose the model to the view.
Place these classes in the ViewModel folder.
Public Class CustomerViewModel Inherits ObservableObject ' Exposing the model to the view through this property. Private _Customer As New Customer Public ReadOnly Property Customer As Customer Get Return _Customer End Get End Property #Region "OKCommand" Private _OKCommand As RelayCommand Public ReadOnly Property OKCommand As RelayCommand Get If _OKCommand Is Nothing Then _OKCommand = New RelayCommand(AddressOf ExecuteOK, AddressOf CanExecuteOK) End If Return _OKCommand End Get End Property Public Sub ExecuteOK() ' Save the models data. Customer.EndEdit() End Sub Public Function CanExecuteOK() As Boolean ' If the model is valid, we can execute the OKCommand. Return Customer.IsValid End Function #End Region End Class
There are a couple of things here - the Customer property and the OKCommand. The customer property simply exposes our customer model to the view. We will bind to that when we create the view. The OKCommand Exposes the ICommand interface. The ICommand interface can be bound to controls that inherit from ButtonBase. This will all make sense when we create the CustomerView.
Since MVVM is not set in stone, there are various way to create your logic layer. Some use the pattern we are laying out here (model injection); while others will use Data Models (or models) as a data map for the data used in the application, otherwise known as ViewModel injection.
As Josh stated in his blog, MVVM is a fluild structure. There is no right or wrong way to structure your project. More advanced MVVM structures (especially those that use TDD, or Test Driven Design or Cross-Platform projects that use one or several Portable Class Libraries) will use a Message Bus to communicate with other ViewModels and one or more Service Buses to send events from the application to the ViewModels or to other applications.
Since busses are out of scope for this tutorial, we will focus on the design of the application. Another thing to keep in mind is that the structure could be ported into Prism or MVVM Light. Although I do not use those frameworks, they provide several tools mentioned above for advanced MVVM senerios such as large enterprise applications.
More by this Author
Models are the data layer of an MVVM application. The models are used to store data in objects (classes) where it can be serialized for transmission to a remote location, or it can be formatted to be stored in a...
The core of the MVVM design contains abstract base classes that will be used throughout your application. The core will always contain the ObserverableObject. This class will implement the INotifyPropertyChanged...