Search code examples
c#wpfmvvmreactiveuiavaloniaui

How do I run a method from a relative ViewModel and get its return value?


To better show my problem, I drew a graph of how my ViewModel hierarchy looks like so far:

ViewModel hierarchy

What I want to achieve is simply call a method from ScriptEditorViewModel and ask it, if the object, which is currently being edited inside EditObjectViewModel has been specified in the script. Later I also want to send some information to ScriptEditorViewModel and make it generate a script for the object if it doesn't exist.

ScriptEditorViewModel and ProjectManagementViewModel are 2 separate tabs in my program, which are basically operating at the same time.

Is it possible to do that and if so, is it a good approach?

Note: I'm currently using ReactiveUI as my MVVM framework but any other MVVM solution is also welcome.


Solution

  • When using MVVM pattern, you want to decouple components.

    • In View part there is xaml with bindings to data and command present in ViewModel.
    • In ViewModel you should keep data that is presented and logic that does something with that data. It is not the wisest thing to couple multiple ViewModels - keep their logic separated. If you have a command method, all data it deals with should be present in its ViewModel. For anything more complex, you shoud consider communicating with some kind of service or database.
    • Hence comes the Model part. Here you want to create the model of something you want to store and not necessary present in a View.

    I don't know if I understood your problem well, but including a database or any kind of 'persistence layer' into your solution should resolve the problem of accessing specific information. You can create some in-memory storage for start.