C#C
C#2y ago
Qwerz

Adding items to an observable collection from 'outside' (MVVM)

Hi all,

I'm developing a desktop application in a small team of developers using WPF. I am responsible for the WPF part of the project while my coworkers are responsible for the core functionality.
We are all new to the MVVM approach, and I'm afraid that I have not grasped it properly despite me having thought that I did.

I'm going to simplify my problem a little for the sake of explaining it without too much detail.
I created a view with an items control. The items control has an ItemsSource binding to an observable collection in the corresponding ViewModel. The goal is to display events (errors, success messages, etc.) in this view, hence the observable collection is one of "messages".
The problem lies in adding events to the collection from across the program. The general structure of the project consists of multiple manager classes handling functions such as getting and setting data from a database, e.g. a "DatabaseManager". Ideally, I would have thought that in my ViewModel, I create a static function "NewEvent" which adds an event to the Observable collection. However, this isn't possible because the ViewModel and its collection are not static. I.e. : a function runs in the DatabaseManager and from there, a new event should be deployed and shown in the view via the observable collection.

What is the correct way to implement this? I assume I could make the collection static and reference the VM directly, but is that the correct way WPF wants me to take?

This is an example of a general problem I seem to be having with the MVVM methodology. I understand the View and ViewModel separation, however I'm utterly uncertain how to connect the UI Framework part with the actual functions in the backbone of any application. The vast majority of tutorials show how to bind a text box and a button to the extent that items are added to a list 'visually'. They never go into detail how to implement functions in the actual backend of an application.

Thanks a lot in Adv.
Was this page helpful?