I am currently developing a new WPF application and have the majority of my business logic layer developed (ie my Models).
I am about implement ViewModel classes to represent one feature of my application. I am quite new to the Model-View-ViewModel pattern and I have a question about which approach would be best to use when implementing my ViewModel classes.
From examples online I have been finding that often the Model is a member of the ViewModel. Using this approach, the ViewModel exposes the properties of the Model-member so that they can be bound to the Model in the View.
For example:
Public Class MyViewModel
Implements INotifyPropertyChanged
Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
Private _myModel As ModelClass
Public Property MyModelPropertyA As Object
Get
Return _myModel.MyModelPropertyA
End Get
Set(ByVal value As Object)
_myModel.MyModelPropertyA = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("MyModelPropertyA")
End Set
Public Property MyModelPropertyB As Object
Get
Return _myModel.MyModelPropertyB
End Get
Set(ByVal value As Object)
_myModel.MyModelPropertyB = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("MyModelPropertyB")
End Set
'.... And so On'
End Class
What I don’t like about this approach is the fact that there are a lot of properties that I will be re-writing.
So, I am considering the option of Inheriting the model class in the ViewModel instead of using a private member.
Like So:
Public Class MyViewModel
Inherits MyModel
Implements INotifyPropertyChanged
Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
'Now all of my properties are inherited'
End Class
The problem with the second approach is that I’m not sure how to convert my models into view models while the application is running.
You can’t set viewModelInstance = ModelInstance.
(But you can set modelInstance = viewModelInstance)
I’m looking for advice on the best approach on how to implement the ViewModel classes.
Do not even think about inheriting your viewModel from model – this will be a hack which nobody will like. If you are too lazy too expose all the properties (BTW resharper can do it automatically) then you can include your model into your viewModel and provide an access to it via some readonly property. But you should still have
INotifyPropertyChangedimplemented in model class.Some code (sorry for C#):
View XAML: