Reputation: 4140
I have an ICommand
implementation which is stand-alone. It modifies information on an entity. The same entity is bound to a View
, as a property of the View's ViewModel
.
What I want to achieve is, the entity (and hence the ViewModel, hence - the View) to update with the new information, after the command is executed. The way I understand it, ICommand
-s are one-way street. They modify the underlying data, but are not supposed to give a direct result.
So I have achieved this by sending a Message
from within the Command at the end of its execution, by using the MVVMLight framework. The View Model which exposes the entity also subscribes to the same message and updates itself, when the message is received (updated info is passed as property of the message).
The added benefit is that other View Models can also subscribe and react to the same event. What 'smells' about it, though, is that the backbone of this implementation is events
. From what I've read, the whole concept of events doesn't fit well within the MVVM pattern. Or cross-VM communication is OK to be done this way?
Example:
Domain Model
First Name
Last Name
Full Name { get { return First Name + Last Name } }
View Model
User Domain Model
, but doesn't store an instance of it
string First Name
string Last Name
string Full Name
(Note: Doesn't know anything about how it's calculated)ICommand Change First Name
MapFromDomainModel(UserDomainModel)
. Invoked when the View Model receives UserDomainChanged
message.Command
Change First Name : ICommand
First Name
in the User Domain Model
UserDomainChanged(UserDomainModel)
messageSee, in this example the View Model doesn't know how Full Name
is calculated and doesn't/shouldn't know that when First Name
is changed, the Full Name
should be changed too. That's why the Command is working directly on the Domain Model and triggers the Message.
Also, I may have other Views on in the Window, which have View Models bound to the same User Domain Model. By subscribing to the same message they can update themselves independently.
Is this a good approach? Is there a better one?
Upvotes: 2
Views: 145