I am rather new to WPF. I’m trying to realize a chat app using Jabber.NET and I would like to follow a correct MVVM architecture. I have the following Models:
BuddyListModel
ChatSessionModel
ChatMessageModel
The following ViewModels:
BuddyListViewModel
ChatSessionsViewModel
ChatMessagesViewModel
Each of the VM contains ObservableCollection<> of corresponding Models.
I instanciate Jabber in BuddyListViewModel (where I’ve put login handling) and all the Event handlers (presence, new message) are in that VM; the problem is that, doing in this way, I must call other VMs methods (AddNewChatSession when a new message arrives,….) from the BuddyListViewModel and I don’t know if this is the right approach for MVVM.
Another problem is that I’m handling ALL the messages in a single ViewModel and think to use filters (in linq, for example) to show the messages in the corresponding ChatSession. Is it a good thing?
I’d create an
ApplicationViewModelthat holds the instance of of your main model (which may be the Jabber object), and pass the instance the other VMs it instantiates so that they can register to handle events that model raises. (I’m assuming, based on your description, that when Jabber receives a message it raises an event and passes the message in theEventArgs.)If you do this, then when a new message arrives, your
ChatSessionsViewModelcan check it to see if it’s in a new session, and create a newChatSessionViewModelif it is. YourChatSessionViewModelcan check the message to see if it belongs to the session, and add it to its collection of messages if it does. These two operations are completely independent of one another.I wouldn’t put all the chat messages in a single collection and then have the session view models filter them – filtering items in a collection is an O(n) operation, and if you’re building a chat client, n is going to get very big. It’s much more logical to have the chat session examine the message as it comes in and capture it if it belongs to the session.
But it really depends on the application. If you approach it this way, there’s the possibility that a message will come in that nothing’s handling, and it’ll get discarded. Is that OK?